How to add image in Flutter (Flutter – Asset Image)

In this article, we will learn how to add images in the flutter app. A flutter app when built has both assets (resources) and code. Assets are available and deployed during runtime. The asset is a file that can include static data, configuration files, icons, and images. The Flutter app supports many image formats, such as JPEG, WebP, PNG, GIF, animated WebP/GIF, BMP, and WBMP. Read more

Syntax:   Image.asset('image name')

Steps to Add an Image:

1. Create a new folder

It should be in the root of your flutter project. You can name it whatever you want, but assets are preferred.
If you want to add other assets to your app, like fonts, it is preferred to make another subfolder named images.



2. Now you can copy your image to assets folder. The path should look like assets/your-Image. Before adding images also check the above-mentioned supported image formats.




3. Register the assets folder in pubspec.yaml file and update it.


a) To add images, write the following code:  

flutter: assets: 
    - assets/yourFirstImagename.jpg 
    - assets/yourSecondImagename.jpg



b) If you want to include all the images of the assets folder then use  this code in  pubspec.yaml file instead of the above code 

flutter: assets: 
             - assets/images/

Note: Take care of the indentation, assets should be properly indented to avoid any error.



4. Insert the image code in the file, where you want to add the

 image.Image.asset('assets/IMG_0479.JPG')

Here is how we can use Asset Image inside our code
import 'package:flutter/cupertino.dart';
import "package:flutter/material.dart";
class home extends StatelessWidget {
const home({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return Material(
color: Colors.lightBlueAccent,
child: Padding(
padding: const EdgeInsets.all(98.0),
child: Center(
child:Column(
children: <Widget>[
Row(
children: const <Widget>[
Expanded(
child: Text(
"name",
style: TextStyle(
color: Colors.red,
fontSize: 20,
fontFamily: 'Roboto',
fontWeight: FontWeight.w700,
fontStyle: FontStyle.normal,
),
),
),
Expanded(
child: Text(
"Images",
style: TextStyle(
fontSize: 20,
fontFamily: 'Roboto',
fontWeight: FontWeight.w700,
fontStyle: FontStyle.normal,
),
),
),

],
),
Container(
child: getAssetImage(),
)

],
)
),
),
);
}
Image getAssetImage() {
//the palce where asset image is located
AssetImage assetimage= AssetImage('assets/IMG_0479.JPG');
//Creating Image Object
Image image= Image(image: assetimage,width: 250.0,height: 250.0,);
return image;



}
}




No comments

Powered by Blogger.