Use Local Images in Flutter
Local Images
Local images are pictures stored in your app. They don’t need the internet to work and load faster. These are ideal for images that don’t change, like logos and icons.
How to Use Local Images
Step 1: Create an Assets Folder
To use local image, first download it from here, then create an ‘assets’ folder in your project and add the downloaded image to this folder.
Step 2: Add Images to the pubspec.yaml File
Now, you need to add images to the pubspec.yaml file. Go to your pubspec.yaml file and add the following code in it:
flutter:
assets:
- assets/learn_flutter.jpg
Save your pubspec.yaml file.
Step 3: Use the Images
To display an image in Flutter, you need to use the Image widget. You can use the Image widget in two ways:
Image.asset(
'assets/learn_flutter.jpg',
width: 150,
height: 150,
)
Image(
image: AssetImage('assets/learn_flutter.jpg'),
width: 150,
height: 150,
)
Example 1: Profile App
In this example, we will create a profile app and add a local image to it.
import 'package:flutter/material.dart';
void main() {
runApp(const ProfileApp());
}
class ProfileApp extends StatelessWidget {
const ProfileApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Profile App',
home: ProfileScreen(),
);
}
}
class ProfileScreen extends StatelessWidget {
const ProfileScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Profile App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const CircleAvatar(
backgroundImage: AssetImage('assets/learn_flutter.jpg'),
radius: 50,
),
const SizedBox(height: 10),
const Text(
'Flutter Tutorial',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 10),
const Text(
'https://flutter-tutorial.net',
style: TextStyle(
fontSize: 16,
color: Colors.blue,
),
),
],
),
),
);
}
}