Sunday, 12 December 2021

Image Picker Flutter - Pick Image From Gallery or Camera

Flutter application that is accessing the camera to take a picture or using the gallery to pick an image then in this tutorial we are going to learn how to access Camera or Gallery in a flutter application. In this Image Picker Example, we are going to use ImagePicker dependency to access the camera/gallery. You can read also How to Capture Video from camera in flutter
dev_dependencies:
  image_picker: ^0.8.3+3
  
How to capture Image from Camera? To capture an image from the camera first we need to create ImagePicker instance This ImagePicker contains method getImage() will return Image File. To get from Camera we need to pass the ImageSource.camera parameter to this getImage().
void _openCamera(BuildContext context)  async{
    final pickedFile = await ImagePicker().getImage(
          source: ImageSource.camera ,
          );
          setState(() {
          imageFile = pickedFile!;
    });
    Navigator.pop(context);
}
we don't know how much time will it take to capture the image from the camera, so we are written this method inside the future method. similarly to pick an image from the gallery we need to pass ImageSource.gallery as a parameter.
void _openGallery(BuildContext context) async{
  final pickedFile = await ImagePicker().getImage(
    source: ImageSource.gallery ,
  );
  setState(() {
    imageFile = pickedFile!;
  });

  Navigator.pop(context);
}
Show Dialog In a flutter With the showDialog() widget we are showing the dialog by returns AlertDialog widget
 Future_showChoiceDialog(BuildContext context)
{
  return showDialog(context: context,builder: (BuildContext context){

    return AlertDialog(
      title: Text("Choose option",style: TextStyle(color: Colors.blue),),
      content: SingleChildScrollView(
      child: ListBody(
        children: [
          Divider(height: 1,color: Colors.blue,),
          ListTile(
            onTap: (){
              _openGallery(context);
            },
          title: Text("Gallery"),
            leading: Icon(Icons.account_box,color: Colors.blue,),
      ),

          Divider(height: 1,color: Colors.blue,),
          ListTile(
            onTap: (){
              _openCamera(context);
            },
            title: Text("Camera"),
            leading: Icon(Icons.camera,color: Colors.blue,),
          ),
        ],
      ),
    ),);
  });
}
   
Download complete source code for Flutter Image Picker example

Flutter API Integration

Python Library Management System Project

C++ Library Management System Project