How to add and use assets in a package — flutter
Sometimes we want to add assets in packages; trust me, it’s not similar to how you do it for apps. It's not complex but different. So, let’s see how we can include assets in our package, and use them in the package as well as how the apps can access those assets.
Include & use assets in packages
To include assets in the package :
- Place the assets folder in /lib folder
- Add it in the pubspec.yaml as
assets:
- lib/assets/
- Now to access the asset we need to call it as — packages/package_name/lib/assets/file_name
//For example the package name is xyz and the file name is abc.txt
//we can access the file as:
final String data =
await rootBundle.loadString('packages/xyz/lib/assets/abc.txt');
It can be used with other functions and widgets as well for eg:
//For example the package name is xyz and the file name is abc.png
//we can access the file as:
AssetImage('packages/xyz/lib/assets/abc.png');
Use package assets in the application
To use package assets in the application we need to include them in pubspec.yaml as :
//For example the package name is xyz and the file name is abc.txt
//The file is placed at "lib/assets/" location in the package
//So we can include it as
assets:
- packages/xyz/assets/abc.txt
There are several ways to access the package asset in the application depending on the asset type :
- If the asset is an image
//For example the package name is xyz and the file name is abc.png
//The file is placed at "lib/assets/" location in the package
//So we can use it as
const AssetImage('assets/abc.png', package: 'xyz');
- If the asset is a text file
//For example the package name is xyz and the file name is abc.txt
//The file is placed at "lib/assets/" location in the package
//So we can use it as
final String data = await rootBundle
.loadString('packages/xyz/assets/abc.txt');
For more details, please check out the flutter docs here
Hope this was fun!!!!
Feel free to drop comments if you face any issues or if you have a finer solution for this.