Back

How to access a asset in a dart function

  • 0
  • Self Hosted
  • Flutter
  • Functions
Lenolium
6 Apr, 2023, 13:20

Hi I am trying to access a asset in my dart function but I don't know how to set the path properly.

TL;DR
To access an asset in a dart function, you can use the `DefaultAssetBundle` or `rootBundle` class. If you have the `BuildContext` available, you can use `DefaultAssetBundle` to access the asset. Here's an example code snippet: ``` Future<String> loadAsset(BuildContext context) async { return await DefaultAssetBundle.of(context).loadString('assets/my_text.txt'); } ``` If you don't have `BuildContext`, you can use `rootBundle` instead. Here's an example: ``` import 'dart:async' show Future; import 'package:flutter/services.dart' show root
rafagazani
6 Apr, 2023, 14:06

Would it be possible to share the code to see how your imports and folder structure are doing?

rafagazani
6 Apr, 2023, 14:13

I have some functions in dart, what I needed to do was import them from the dart project name: pubspec.yaml: name: my_function

in the archives: import 'package:my_function/modules/model/any_files.dart’;

Lenolium
7 Apr, 2023, 12:08
Lenolium
7 Apr, 2023, 12:09

For example rootBundle.load("lib/example.txt'')

Lenolium
7 Apr, 2023, 12:10
pandemoniun
7 Apr, 2023, 13:45

import 'dart:async' show Future; import 'package:flutter/services.dart' show rootBundle;

Future<String> loadAsset() async { return await rootBundle.loadString('assets/my_text.txt'); }

pandemoniun
7 Apr, 2023, 13:46

Or if you have the BuildContext (inside a widget) you can use DefaultAssetBundle. This is recommended because it allows switching asset bundles at runtime, which is useful for multilingual assets.

Future<String> loadAsset(BuildContext context) async { return await DefaultAssetBundle.of(context).loadString('assets/my_text.txt'); }

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more