Search code examples
flutterflutter-dependencies

How to open phone gallery or camera or any other medium available using ImagePicker in Flutter.?


I need some help regarding the image picker plugin in flutter. I want to let users select images from wherever he/she wants like a camera, gallery, Google drive/photos, or anywhere else not just only one option.

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

class UserImagePicker extends StatefulWidget {
  @override
  _UserImagePickerState createState() => _UserImagePickerState();
}

class _UserImagePickerState extends State<UserImagePicker> {
  File _pickedImage;

  void _pickImage() async {
    final pickedImageFile =
        await ImagePicker().getImage(source: ImageSource.gallery);
    setState(() {
      _pickedImage = File(pickedImageFile.path);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        CircleAvatar(
          radius: 40,
          backgroundColor: Colors.grey,
          backgroundImage:
              _pickedImage != null ? FileImage(_pickedImage) : null,
        ),
        FlatButton.icon(
          textColor: Theme.of(context).primaryColor,
          onPressed: _pickImage,
          icon: Icon(Icons.image),
          label: Text('Add Image'),
        ),
      ],
    );
  }
}

Solution

  • Here's a rework of your _pickedImage to show an alert dialog so the user can choose the source of its image.

    void _pickedImage() {
      showDialog<ImageSource>(
        context: context,
        builder: (context) => AlertDialog(
          content: Text('Choose image source'),
          actions: [
            ElevatedButton(
              child: Text('Camera'),
              onPressed: () => Navigator.pop(context, ImageSource.camera),
            ),
            ElevatedButton(
              child: Text('Gallery'),
              onPressed: () => Navigator.pop(context, ImageSource.gallery),
            ),
          ],
        ),
      ).then((ImageSource? source) async {
        if (source == null) return;
    
        final pickedFile = await ImagePicker().pickImage(source: source);
        if (pickedFile == null) return;
    
        setState(() => _pickedImage = File(pickedFile.path));
      });
    }