In Flutter, the AssetBundle feature is used by developers to manage and organize resources within their applications. In this article, we will learn about AssetBundle in Flutter in Detail.
What is AssetBundle in Flutter?
AssetBundle in Flutter acts like a centralized repository that stores all the static assets required by the application. To put it in simple words it allows users to bundle together the different types of media content like icons, images, audio files, fonts, JSON data, etc into a collection and access them when the app is run.
The AssetBuilder not only makes the application development process smoother but also optimizes the application's performance. It also enhances the user experience, making it visually more appealing and user-friendly.
Methods Associated with AssetBundle
The AssetBundle in Flutter provides various methods to load different types of assets. These methods provide flexibility and make it easier for developers to manage and access various types of assets in their Flutter application. Let us understand each of them one by one.
1. DefaultAssetBundle.of(BuildContext context)
This method gets the AssetBundle for the current BuildContext in the application. It is preferred over using rootBundle directly because the DefaultAssetBundle.of(context) lets the parent widgets provide a different AssetBundle if needed (for example, for testing or changing the assets based on language).
AssetBundle bundle = DefaultAssetBundle.of(context);
2. loadString(String key)
The loadString method loads a string from the asset bundle, commonly used for loading text files, JSON data, etc.
String data = await DefaultAssetBundle.of(context).loadString('assets/data/sample.json');
3. load(String key)
This method loads an asset as a ByteData object, which is useful for binary files.
ByteData data = await DefaultAssetBundle.of(context).load('assets/data/sample.dat');
4. loadStructuredData<T>(String key, Future<T> parser(String value))
This method loads a text asset and parses it as structured format.
T data = await DefaultAssetBundle.of(context).loadStructuredData('assets/data/sample.json', (value) async {
return json.decode(value);
});
5. loadBuffer(String key)
This loads an asset as an ImmutableBuffer, useful for binary data with immutable properties that is the data that does not change.
ImmutableBuffer buffer = await DefaultAssetBundle.of(context).loadBuffer('assets/data/sample.dat');
6. loadAsset(String key)
This loads an asset as an AssetData, useful for retrieving metadata and data simultaneously.
AssetData assetData = await DefaultAssetBundle.of(context).loadAsset('assets/data/sample.dat');
7. list(String path)
The above method lists all assets within a given directory path.
List<String> assets = await DefaultAssetBundle.of(context).list('assets/data/');
Step By Step Implementation of AssetBundle Flutter
Step 1 : Creating the assets files
To Implement the AssetBundle feature we first need to create the directory structure for our assets and static resources in the root project directory.
Creating the assets filesStep 2 : Setting up Assets in 'pubspec.yaml'.
Next, we have to add the assets to be included in the application, under the assets section in the pubspec.yaml file, ensuring that the correct indentation is followed.
Setting up Assets in 'pubspec.yaml'.If the asset path is incorrect, Flutter won't be able to locate and load the asset. This can cause the app to crash or display errors when trying to access the missing asset. Therefore, it is important to ensure correct indentation and paths are provided in the pubspec.yaml file.
Step 3 : Loading the assets
Add the resource file to the assets folder. Ensure that the pubspec.yaml includes the asset path. Now, we are ready to use it in the Flutter widget.
Example for adding an image
First, add the image (example.png) in the '/assets/images/' folder. Then add the asset path in pubspec.yaml as shown below.
add the asset path in pubspec.yamlNow, we can add the image in the application widget easily by using the Image.asset in the code.
Dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('AssetBundle Example'),
),
body: Center(
child: Image.asset('assets/images/example.png'),
),
),
);
}
}
Similarly, we do this for audio assets, font assets, JSON assets, and Text and other data assets.
Accessing Assets from Another Package
Some libraries provide built-in support for accessing assets from another package, while for others we have to specify the path manually.
Lottie
The 'Lottie.asset' constructor provides a package parameter that allows developers to specify the package name directly where the asset is stored.
Dart
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Lottie Example')),
body: Center(
child: Lottie.asset(
'assets/animations/example.json',
package: 'package_name',
),
),
),
);
}
}
Rive
Rive does not have a built-in option to specify the package. So we need to provide the path in the format packages/<package-name>/<asset-path>.
Dart
import 'package:flutter/material.dart';
import 'package:rive/rive.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Rive Example')),
body: Center(
child: RiveAnimation.asset(
'packages/your_package_name/assets/animations/example.riv',
),
),
),
);
}
}
Conclusion
With AssetBundle in Flutter, we can create beautiful feature-rich applications. The property not only simplifies the workflow for Flutter developers but also improves the overall quality of Flutter apps.
Similar Reads
Flutter - Asset Image
Flutter is an open-source, cross-platform UI development kit developed by Google. It is gaining popularity these days, as the app made in Flutter can run on various devices regardless of their platform. It is majorly used to develop applications for Android and iOS, as a single app made in Flutter c
2 min read
Flutter - DevTools
DevTools is a tooling suite for Flutter and Dart developers consisting of layout inspection tools, performance tools, memory tools basically all the debugging tools that you need to be an efficient and effective Flutter developer bundled into a single web suite. Usage of DevTools: The Flutter DevToo
11 min read
AnimatedList Flutter
AnimatedList in Flutter is a dynamic list component that enables us to insert and remove elements dynamically. AnimatedList is a list that animates the items when they are removed or inserted enhancing the user experience. As we all using ListView in Flutter lists for displaying a collection of item
8 min read
Container class in Flutter
Container class in flutter is a convenience widget that combines common painting, positioning, and sizing of widgets. A Container class can be used to store one or more widgets and position them on the screen according to our convenience. Basically, a container is like a box to store contents. A bas
8 min read
Flutter - RFlutter Alerts
In Flutter, rflutter_alert is useful to create alerts in applications easily. It is a customizable and best way to create alerts in Flutter. In this article, we will see the different styles of alerts we can create with this awesome Flutter library. Follow the article to learn about it. Adding the d
4 min read
Flutter - Load JSON Assets
In Flutter, you can load JSON assets using the rootBundle method from the flutter/services package. First, create a new Flutter project by running the following command in your terminal. Step by Step Implementation Step 1: Create a New Project in Android Studio To set up Flutter Development on Andro
3 min read
Flutter - Load Text Assets
In Flutter, you can easily load text assets such as JSON files, configuration files, or plain text files into your app's memory at runtime. This allows you to access the data contained in these files and use it to populate your app's UI or perform other operations. To load text assets in Flutter, yo
3 min read
AnimatedWidget flutter
In Flutter, creating these visually attractive and smooth Animations can be a challenging task, as everything in Flutter is a Widget, and would need strong control over the widget state and transitions. For that, we have the "AnimatedWidget" class in Flutter.What is AnimatedWidget in Flutter?'Animat
7 min read
Flutter - Dismissible Widget
The Dismissible widget in Flutter is used to create items that can be dismissed by swiping them off the screen. It's commonly used in lists or grids where you want to provide a way for users to remove items with a swipe gesture. In this article, we are going to implement the Dismissible widget and e
4 min read
Flutter - Carousel Slider
Carousel Slider is one of the most popular image sliders used nowadays in most apps. These carousel sliders are mostly seen on various eCommerce sites such as Amazon, Flipkart, Myntra, and many more. Displaying the images in a slider gives an attractive User Experience. As these sliders are automate
4 min read