AssetImage
- Flutter course
- Beginner
- Lesson 76/99
- 4 min
Load local images with AssetImage.
What is AssetImage?
AssetImage is the class used to load local images bundled into your app. Image files are placed in the project's assets/ folder and declared in pubspec.yaml. You show the image with either AssetImage(...) or the shortcut Image.asset(...).
Image(
image: AssetImage('assets/logo.png'),
)
// or the shortcut:
Image.asset('assets/logo.png')Declaring assets in pubspec.yaml
In pubspec.yaml you add an assets list under the flutter section. If you write a folder path, all files inside are bundled; you can also list individual files. After changes you must do a hot restart; hot reload is not enough.
flutter:
uses-material-design: true
assets:
- assets/
- assets/icons/Practice Show an image with AssetImage
Return an Image widget that shows assets/logo.png using AssetImage. Place it inside a Center in the Scaffold body.
Starter code
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: // buraya yaz
,
),
),
);
}
}Sample solution
import 'package:flutter/material.dart';
void main() {
print('AssetImage: assets/logo.png');
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Image(
image: AssetImage('assets/logo.png'),
),
),
),
);
}
}Expected output
AssetImage: assets/logo.png
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the first step to bundle a local image into the app?
- Place the image in the lib folder
- Put the image in the assets folder and declare it in pubspec.yaml Correct answer
- Download the image from the internet
- Embed the image inside main.dart
Explanation: Images loaded with AssetImage are bundled into the app package; the file must be placed in the assets folder and declared in pubspec.yaml.
2 Load an image with AssetImage
Image(
image: ____,
)
Image(
image: AssetImage('assets/logo.png'),
)
Explanation: AssetImage loads an image from a local asset path; it does not take a URL or file path.
3 AssetImage parts
| Term | Meaning |
|---|---|
assets/ klasörü |
Where images are stored |
pubspec.yaml |
The file where asset paths are declared |
Image.asset |
Shortcut constructor |
hot restart |
Required after asset changes |