πͺ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.
Last updated
Was this helpful?