skip to Main Content

I’m trying to use the image_picker 1.1.2 package in my project to select images from the gallery, but the image I picked doesn’t show up.
This is the important part of the code:

Widget build(BuildContext context) {
File? image;

Future pick() async {
  final ImagePicker picker = ImagePicker();
  final picked = await picker.pickImage(source: ImageSource.gallery);
  File file = File(picked!.path);
  setState(() {
    image = file;
  });
}

return Scaffold(
  backgroundColor: Colors.white,
  appBar: AppBar(
    foregroundColor: Colors.white,
    backgroundColor: const Color.fromRGBO(34, 30, 204, 50),
    title: Text('new'.tr()),
  ),
  body: Container(
    padding: const EdgeInsets.only(top: 20, right: 10, left: 10),
    child: Center(
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const SizedBox(width: 20),
              image == null
                  ? const Text('No photo')
                  : Image.file(
                      image!,
                      width: 100,
                      height: 100,
                      fit: BoxFit.fill,
                    ),
              IconButton(onPressed: pick, icon: const Icon(Icons.photo))
            ],
          ),
          Form(
              key: key3,
              child: Expanded(
                child: ListView(
                  children: [...

2

Answers


  1. The image is declared inside build function, so it is a local variable and is reset in the rebuild. It should be a property of the State instead.

    File? image;
    Widget build(BuildContext context) {
    
    Future pick() async {
    
    Login or Signup to reply.
  2. Yes, PurplePolyhedron’s answer is correct.
    To explain in more detail, when you call setState() in the State class, State.build() is always called again.
    So when you click on the IconButton and call the pick method,
    the following process happens:

    Widget build(BuildContext context) { // 2. build method called again because of setState()
    File? image; // 3. image is initialized again to null
    
    Future pick() async {
      final ImagePicker picker = ImagePicker();
      final picked = await picker.pickImage(source: ImageSource.gallery);
      File file = File(picked!.path);
      setState(() {
        image = file; // 1.file you selected in your gallery is setted image.
      });
    }
    ...
    

    That’s why the image doesn’t appear.
    So if it is managed as a State outside the build, it will not be reinitialized after setState.

    File? image;
    Widget build(BuildContext context) {
    ...
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search