flutterdartimagepicker

How can I display image picked from image picker


I have this code. I can pick an image on my gallery but it's not displaying. Need help on that, thanks !

import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:image/image.dart' as Im;
import 'package:path_provider/path_provider.dart';
import 'package:image_picker/image_picker.dart';
import 'package:uuid/uuid.dart';
import 'package:flutter_dev/home.dart';

class Add extends StatefulWidget {
  const Add ({super.key});

  @override
  State<Add> createState() => _AddState();
}

class _AddState extends State<Add> {

  File? imageFile;

  selectFile() async {
    XFile? file = await ImagePicker().pickImage(
    source: ImageSource.gallery, maxHeight: 1800, maxWidth: 1800);
    
    if (file != null) {
      setState(() {
        imageFile = File(file.path);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return FractionallySizedBox(
        heightFactor: MediaQuery.of(context).size.height * 0.00095,
        child: Center(
            child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (imageFile != null)
              Expanded(
              child : Container(
              child: Image.file(
                File(imageFile!.path),
                fit: BoxFit.cover,
              ),
             ),
            ),
            Column(
              children: [
                ElevatedButton(
                    onPressed: selectFile, child: const Text('Select file')),
                ElevatedButton(
                    onPressed: () {}, child: const Text('Open camera')),
                ElevatedButton(
                    onPressed: () {}, child: const Text('Upload file')),
              ],
            )
          ],
        )
      )
    );
   }
  }

Solution

  • try this:

    instead of this:

        child: Image.file(
                File(imageFile!.path),
                fit: BoxFit.cover,
              ),
    

    replace with this:

    //...
        child: Image.file(
                imageFile!,
                fit: BoxFit.cover,
              ),
    

    and change this:

            ElevatedButton(
                    onPressed: selectFile, child: const Text('Select file')),
    

    with this:

            ElevatedButton(
                    onPressed: () async { await selectFile();}, child: const Text('Select file')),