In this example, we are going to show you how to pick a single image from Gallery and show it in the Flutter app. You may need an image picker for different kinds of forms. See the example below:
Read this also: How to Make Multiple Image Picker in Flutter App
First, you need to add image_picker package to your project by adding following lines in pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
image_picker: ^0.8.5+3
Now, import the package to your script:
import 'package:image_picker/image_picker.dart';
Declare the object for Image Picker:
ImagePicker picker = ImagePicker();
To pick an image from Gallery:
XFile? image = await picker.pickImage(source: ImageSource.gallery);
See this also: How to use Image Picker and upload file to PHP server
You can display the picked image on the widget tree:
import 'dart:io';
Image.file(File(image!.path))
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
class Home extends StatefulWidget{
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
ImagePicker picker = ImagePicker();
XFile? image;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Image Picker from Gallery"),
backgroundColor: Colors.redAccent
),
body: Container(
padding: EdgeInsets.only(top:20, left:20, right:20),
alignment: Alignment.topCenter,
child: Column(
children: [
ElevatedButton(
onPressed: () async {
image = await picker.pickImage(source: ImageSource.gallery);
setState(() {
//update UI
});
},
child: Text("Pick Image")
),
image == null?Container():
Image.file(File(image!.path))
],)
)
);
}
}
See this also: How to Open Image with Image Picker, Crop and Save in Flutter
In this way, you can pick image from gallery in Flutter.
Please Wait...
No any Comments on this Article