i want to create a function in flutter to pick image from gallery and camera in my page. can someone help me with this code please.
import 'package:flutter/material.dart';
class Productdetails extends StatefulWidget {
const Productdetails({super.key});
@override
State<Productdetails> createState() => _ProductdetailsState();
}
class _ProductdetailsState extends State<Productdetails> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.orange,
title: const Text('Product List'),
titleTextStyle: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 22,
wordSpacing: 2.5,
color: Colors.black),
centerTitle: true,
actions: [
IconButton(onPressed: () {}, icon: const Icon(Icons.save)),
],
),
body: const Padding(padding: EdgeInsets.symmetric(vertical: 20,horizontal: 20),
child: Text(
'Product Image',style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold),
),
),
);
}
}
2
Answers
You can you either the image_picker or file_picker package.
The image_picker has a future function that allows you to pick image from gallery or camera and it returns a file object. You can use the path to that file to set your image.
The file_picker allows you to pick any file from your storage either image, video etc. But you can put restrictions on it to select only images.
This is part of your State class in a Stateful widget:
Code snippet to display the image in an Avatar:
In case image loading/clicking fails, you should have a dafault image in your project assets. Include it in your pubspec.yaml file.