πŸͺ„Working with Assets

Assets are the files your app needs to function, like images, fonts, or data files. Here’s how you can include and use assets in your Flutter app.

1. Adding Assets to Your Project πŸ—‚οΈ

First, create a folder named assets in the root of your project and place your asset files in it.

2. Updating pubspec.yaml πŸ“„

Next, update your pubspec.yaml file to include the assets. Under flutter:, add an assets: section like so:

flutter:
  assets:
    - assets/

3. Using Images from Assets πŸ“Έ

Now that you’ve added your assets, you can use them in your app. Here’s how to display an image:

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('Assets Example'),
        ),
        body: Center(
          child: Image.asset('assets/image.png'),
        ),
      ),
    );
  }
}

4. Using Custom Fonts πŸ…°οΈ

You can also include custom fonts in your assets. First, create a fonts folder inside assets, then update your pubspec.yaml:

flutter:
  fonts:
    - family: CustomFont
      fonts:
        - asset: assets/fonts/CustomFont-Regular.ttf

Now, you can use your custom font in your app:

Text(
  'Hello, Flutter University!',
  style: TextStyle(
    fontFamily: 'CustomFont',
    fontSize: 20,
  ),
)

5. Loading and Using Data Files πŸ“‚

You can read data from files stored in your assets as well:

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

Assignments πŸ“

Time for some hands-on practice:


With these assignments, you'll get a practical understanding of working with assets in Flutter.

Congratulations you're done with the basics of flutter!

Let's move to intermediate stuff now.

Last updated