Open In App

AssetBundle Flutter

Last Updated : 08 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

dir
Creating the assets files

Step 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.

yaml
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.

exam
add the asset path in pubspec.yaml

Now, 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.


Next Article
Article Tags :

Similar Reads