flutter image picker crashing

925 Views Asked by At

I am trying to use the image_picker on flutter app everything is fine until gallery open i choose the image then the app will crash and restart.

before this it was working fine like 1 month ago but now it is not. is there any solution

this is my code.

  Future _pickImage() async {
    try {
      final image = await ImagePicker().pickImage(source: ImageSource.gallery);

      if (image == null) return;
      final imageTemporary = File(image.path);
      setState(() {
        _image = imageTemporary;
      });
    } catch (error) {
      print("error: $error");
    }
    // setState(() {
    //   _image = img;
    // });
  }
  File? _image;

  Future _pickImage() async {
    try {
      final image = await ImagePicker().pickImage(source: ImageSource.gallery);

      if (image == null) return;
      final imageTemporary = File(image.path);
      setState(() {
        _image = imageTemporary;
      });
    } catch (error) {
      print("error: $error");
    }
 
  }
1

There are 1 best solutions below

0
On

This code snippet can help you.

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


class PickImage extends StatefulWidget {
  const PickImage({Key? key}) : super(key: key);

  @override
  State<PickImage> createState() => _PickImageState();
}

class _PickImageState extends State<PickImage> {
  XFile? _image;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: SingleChildScrollView(
        child: Column(
          children: [
            TextButton(
                onPressed: _imageHandler, child: const Text("Pick image")),
            if (_image != null) Image.file(File(_image!.path))
          ],
        ),
      ),
    );
  }

  Future _imageHandler() async {
    try {
      final XFile? imagePicker =
          await ImagePicker().pickImage(source: ImageSource.gallery);
      if (imagePicker != null) {
        _image = imagePicker;
      } else {
        /// user canceled
      }
    } catch (e) {
      print(e);
    }
  }
}