Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Image_Picker doesn't pick image from gallery and return to app

Here is a what's happening : I'm trying to upload an image from gallery to my app on iOS simulator. Image Picker opens the gallery but can't select an image and return to app. Here's my simple code:

  File _image;
  final picker = ImagePicker();

  Future getImage() async {
    final pickedFile = await picker.getImage(source: ImageSource.gallery);

    setState(() {
      if (pickedFile != null) {
        _image = File(pickedFile.path);
      } else {
        print('No image selected.');
      }
    });
  }

and my widget:

body: Center(
        child: _image != null ? Image.file(_image) : Text('no Image'),
),

Thank you all in advance


1 Answers

For the iOS, as stated in the documentation, you'll need some config in the native side relating to permission:

Add the following keys to your Info.plist file, located in /ios/Runner/Info.plist:

  • NSPhotoLibraryUsageDescription - describe why your app needs permission for the photo library. This is called Privacy - Photo Library Usage Description in the visual editor.
  • NSCameraUsageDescription - describe why your app needs access to the camera. This is called Privacy - Camera Usage Description in the visual editor.
  • NSMicrophoneUsageDescription - describe why your app needs access to the microphone, if you intend to record videos. This is called Privacy - Microphone Usage Description in the visual editor.

Other than that, it should work perfectly fine with your code. The image should be fit within a Flexible like this, or maybe a SizedBox to avoid overflowing:

import 'dart:io';

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

void main() {
  runApp(MaterialApp(
    home: SampleScreen(),
  ));
}

class SampleScreen extends StatefulWidget {
  @override
  _SampleScreenState createState() => _SampleScreenState();
}

class _SampleScreenState extends State<SampleScreen> {
  File _image;
  final picker = ImagePicker();

  Future getImage() async {
    final pickedFile = await picker.getImage(source: ImageSource.gallery);

    setState(() {
      if (pickedFile != null) {
        _image = File(pickedFile.path);
      } else {
        print('No image selected.');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            FlatButton(onPressed: () => getImage(), child: Text('Press me')),
            Flexible(child: _image != null ? Image.file(_image) : Text('no Image')),
          ],
        ),
      ),
    );
  }
}
like image 149
Bach Avatar answered Oct 27 '25 20:10

Bach