Managing Assets in Flutter: Images, Fonts, and Data

Techdynasty
2 min readOct 5, 2023

--

Working with assets in Flutter involves managing and accessing files that are bundled with your app. These files can include images, fonts, JSON data, and more. Here are some brief notes, examples, and code snippets to help you understand how to work with assets in Flutter:

This basic flow outlines the process of how assets are utilized in a Flutter app, from the user interaction to the display of assets in the user interface.

Folder Structure :

  • In your Flutter project, create a folder named assets in the root directory. Place your asset files inside this folder.
project_root/
├── assets/
│ ├── images/
│ │ ├── sample.jpg
│ ├── data/
│ │ ├── sample.json
│ ├── fonts/
│ │ ├── custom_font.ttf

Adding Assets to pubspec.yaml:

  • Open your pubspec.yaml file and add the assets you want to include. Indentation matters here.
flutter:
assets:
- assets/images/
- assets/data/
- assets/fonts/

Accessing Images :

  • To access images, you can use the Image.asset widget.
Image.asset('assets/images/sample.jpg');

Accessing JSON Data :

  • You can use the rootBundle to load JSON data.
import 'package:flutter/services.dart' show rootBundle;
// ...
Future<void> loadJsonData() async {
final jsonString = await rootBundle.loadString('assets/data/sample.json');
// Parse the JSON string
final jsonData = json.decode(jsonString);
}

Accessing Fonts :

  • To use custom fonts, specify the font file in your TextStyle.
Text(
'Custom Font Text',
style: TextStyle(
fontFamily: 'CustomFont',
),
)

Asset Images in pubspec.yaml:

  • If you want to use an image path dynamically, you can use the package keyword in your asset path.
flutter:
assets:
- packages/my_package/assets/images/

Working with SVG Images :

  • To use SVG images, you can use the flutter_svg package.
dependencies:
flutter_svg: ^0.22.0
import 'package:flutter_svg/flutter_svg.dart';

// ...

SvgPicture.asset(
'assets/images/sample.svg',
semanticsLabel: 'Sample SVG Image',
)

Loading Fonts Dynamically :

  • You can load fonts dynamically using the flutter/services.dart package.
import 'package:flutter/services.dart' show ByteData, rootBundle;

Future<ByteData> loadCustomFont() {
return rootBundle.load('assets/fonts/custom_font.ttf');
}

Remember to run flutter pub get after making changes to your pubspec.yaml file. Flutter will include the specified assets in your app during the build process.

By following these steps, you can effectively work with assets in your Flutter app, whether they are images, JSON data, fonts, or other files bundled with your project.

Every little change has a ripple effect.

--

--

Techdynasty
Techdynasty

Written by Techdynasty

Skilled software developer bridging tech & business needs. Crafting efficient & elegant code for high-quality solutions. https://x.com/Tjanhvi

Responses (1)