Flutter Image Picker doesn't pick image from Album/Gallery

Viewed 1451

I'm trying to implement imagepicker library in my app. My app runs without any errors but I can't pick/select images from the album/gallery. On selecting the image the app should display the image in the body but nothing happens. I have to tap on Cancel to go back to the main screen. I should also mention that the console returns null for the print statement print('image: $image');

Kindly help.

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        brightness: Brightness.dark,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
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('image: $image');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Picker'),
      ),
      body: Center(
        child: image == null
            ? Text('No image selected.')
            : Image.file(image),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: getImage,
        tooltip: 'Pick Image',
        child: Icon(Icons.add_a_photo),
      ),
    );
  }
}
1 Answers

Try with the below code

   Future getImage() async {
        File pickedFile = await picker.getImage(source: ImageSource.gallery);
            if (pickedFile != null) {
                setState(() {
                    image = File(pickedFile.path);
                });
             } else {
                 print('image: $image');
             }
    }
Related