Import Image AssetFiles to Flutter
Applications have some important images, icons, font styles, music and videos, etc. Except for imports using the internet, we can also store them inside the application. We can import different files as assets in Flutter.
So in this tutorial, we learn to import images asset files in Flutter.
Storing in the Project Directory
To import assets, we need to store them in the same directory as the project directory. The project structure looks as follows.
Importing the Assets
Two images are stored in the assets folder. To import asset files we need to modify our pubspec.yaml file. So open it and under the flutter section as in the following image, there is a section commented as assets
So to import the asset image we can reference the relative path of each image as follows.
assets:
- assets\star.png
- assets\thunder.png
Also, we can directly import the folder as follows. Just provide the path of the directory they are stored following a forward slash.
assets:
- assets/
Using Asset Files
Now we have imported the assets, let's use them in our app. We can import Asset Image using the AssetImage image provider. Here is the syntax for using an image in your assets.
AssetImage("star.png"),
The simple syntax is passing the location of the image with the image file name. Suppose the path of the image would be as assets > images > star.png, then the syntax would be as follows.
AssetImage("images/star.png"),
Here is a small example.
import 'package:flutter/material.dart';
class AssetImageTutorial extends StatelessWidget {
const AssetImageTutorial({Key? key, required this.title}) : super(key: key);
final String title;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Image(
width: MediaQuery.of(context).size.width / 2,
image: const AssetImage("star.png"),
),
),
Image(
width: MediaQuery.of(context).size.width,
image: const AssetImage("thunder.png"),
),
],
),
);
}
}
Subscribe to my newsletter
Read articles from Manav Sarkar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by