Flutter 显示从图库中选取的图像

Flutter display image picked from gallery

我只是想挑选一张图片并将其显示在我的应用程序中。为此,我使用 Flutter Image Picker。我添加了所有依赖项,我可以 select 图片但我无法显示它...

这是我试过的:

class _AddMemoryPageState extends State<AddMemoryPage> {
  final picker = ImagePicker();
  late Future<PickedFile?> pickedFile;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.secondary,
      body: SafeArea(
        child: Column(
          children: [
            Row(
              children: [
                Padding(
                  padding: EdgeInsets.only(
                    top: 15,
                    left: 25,
                  ),
                  child: IconButtonWithExpandedTouchTarget(
                    onTapped: () {
                      Navigator.pop(context);
                    },
                    svgPath: 'assets/icons/down.svg',
                  ),
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                IconButtonWithExpandedTouchTarget(
                  onTapped: () async {
                    pickedFile = picker
                        .getImage(
                          source: ImageSource.camera,
                        )
                        .whenComplete(() => {setState(() {})});
                  },
                  svgPath: 'assets/icons/camera.svg',
                ),
                SizedBox(
                  width: scaleWidth(50),
                ),
                IconButtonWithExpandedTouchTarget(
                  onTapped: () async {
                    pickedFile = picker
                        .getImage(
                          source: ImageSource.gallery,
                        )
                        .whenComplete(() => {setState(() {})});
                  },
                  svgPath: 'assets/icons/gallery.svg',
                ),
              ],
            ),
            FutureBuilder(
              future: pickedFile,
              builder: (context, data) {
                if (data.hasData) {
                  return Container(
                    height: 200.0,
                    child: Image.file(
                      data.data as File,
                      fit: BoxFit.contain,
                      height: 200.0,
                    ),
                    color: Colors.blue,
                  );
                }
                return Container(
                  height: 200.0,
                  color: Colors.blue,
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

但是这不起作用:

LateInitializationError: Field 'pickedFile' has not been initialized.

我在这里错过了什么?处理这个问题的正确方法是什么?我找不到任何最新的 tutorial/docs。如果您需要更多信息,请告诉我!

可以尝试在 setState 中初始化 'pickedFile' 吗?并且 PickedFile 类型不是文件类型,因此按照 image_picker 文档 final pickedFile = await _picker.getImage(...); final File file = File(pickedFile.path);.

中所述,将其转换为“Image.file(data.data.path)”

您基本上忘记了在文件中转换 de PickerFile 并初始化变量 pickedFile late Future<PickedFile?> pickedFile = Future.value(null);

要转换文件中的 PickerFile,您只需要做:

File(data.data!.path)

我对你的代码做了一些修改,现在可以显示图像了:

  final picker = ImagePicker();
  late Future<PickedFile?> pickedFile = Future.value(null);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blueGrey,
      body: SafeArea(
        child: Column(
          children: [
            Row(
              children: [
                Padding(
                  padding: EdgeInsets.only(
                    top: 15,
                    left: 25,
                  ),
                  child: IconButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    icon: Icon(Icons.download_rounded),
                  ),
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                IconButton(
                  onPressed: () async {
                    pickedFile = picker.getImage(source: ImageSource.camera).whenComplete(() => {setState(() {})});
                  },
                  icon:Icon(Icons.add)
                ),
                SizedBox(
                  width: 100,
                ),
                IconButton(
                  onPressed: () async {
                    pickedFile = picker
                        .getImage(
                      source: ImageSource.gallery,
                    )
                        .whenComplete(() => {setState(() {})});
                  },
                  icon:Icon(Icons.photo_camera_back),
                ),
              ],
            ),
            FutureBuilder<PickedFile?>(
              future: pickedFile,
              builder: (context, snap) {
                if (snap.hasData) {
                  return Container(
                    child: Image.file(
                      File(snap.data!.path),
                      fit: BoxFit.contain,
                    ),
                    color: Colors.blue,
                  );
                }
                return Container(
                  height: 200.0,
                  color: Colors.blue,
                );
              },
            ),
          ],
        ),
      ),
    );
  }

这是一个简单版本的图像拾取和在小部件上显示图像。希望这对你有用

ImagePicker picker = ImagePicker();
var imageFile;
_getFromGallery() async {
var pickedFile = (await picker.pickImage(
 source: ImageSource.gallery,
  ));
if (pickedFile != null) {
 setState(() {
 imageFile = File(pickedFile.path);
  });
}
}
Widget _imageSection() {
  return (imageFile == null)
     ? Container(
           width:
           MediaQuery.of(context).size.width,
           height: 220,
           child: Card(
                  elevation: 3.0,
                   color: Colors.white,
                   shadowColor: Colors.grey,
                   child: Text("No image selected"),
                  ),
                  )
             : Container(
              width: MediaQuery.of(context).size.width,
               height: 220,
              child: Column(
             children: [
                Image.file(imageFile,
               fit: BoxFit.cover,
                 ),
               ],
             ),
          );
       }

     @override
      Widget build(BuildContext context) {
         return Scaffold(
           appBar: AppBar(
          leading: IconButton(
            onPressed: () {},
            icon: const Icon(Icons.exit_to_app),
           ),
            ),
       body: SingleChildScrollView(
        child: Center(
  child: Column(
      mainAxisAlignment:
          MainAxisAlignment.start,
      children: <Widget>[
        Container(
          child: Padding(
            padding: const EdgeInsets.fromLTRB(
                0, 0, 0, 0),
            child: ElevatedButton(
              onPressed: () {
                _getFromGallery();
                print(imageFile);
              },
              child: Text(
                  'Select Photo'),
            ),
          ),
        ),
        _imageSection(),
      ]),
      ),
    ),
   );
  }