简体   繁体   English

获取在 flutter 的列表视图中工作的图像

[英]Get images working in a listview in flutter

I have a problem getting images using imagePicker to work in a listview.我在使用 imagePicker 获取图像以在列表视图中工作时遇到问题。 When you press one of the containers in the listview you should be able to choose an image from the gallery.当您按下列表视图中的一个容器时,您应该能够从图库中选择一个图像。 This works the first time but then I get a RangeError (index) Invalid value: Only valid value 0: 1 on the rest of the boxes (se the images down below).这第一次有效,但后来我得到一个 RangeError (index) Invalid value: Only valid value 0: 1 on the rest of the box(见下图)。 I am as you can see trying to use the index to check if the element has any data but I dont think Im getting it right.正如你所看到的,我试图使用索引来检查元素是否有任何数据,但我认为我没有做对。 Any suggestions code examples please!请提供任何建议的代码示例!

Future _getImage() async {
    final image = await ImagePicker().pickImage(source: ImageSource.gallery);
    setState(() {
      //_image = image;
      _imageList.add(image!);

      //print('first element: ${_imageList!.isEmpty}');
      //print('second element: ${_imageList!.}');
    });
  }
   

 Padding(
                    padding: const EdgeInsets.symmetric(
                        vertical: 20.0, horizontal: 20.0),
                    child: Container(
                      height: 130.0,
                     
    
                    child: ListView.separated(
                          separatorBuilder: (context, index) => SizedBox(
                                width: 5.0,
                              ),
                          scrollDirection: Axis.horizontal,
                          itemCount: 5,
                          itemBuilder: (BuildContext context, int index) {
                            
                            return _imageList?.isEmpty ?? true
                                ? GestureDetector(
                                    onTap: _getImage,
                                    child: Container(
                                      height: 40.0,
                                      width: 150.0,
                                      decoration: BoxDecoration(
                                        border: Border.all(color: Colors.grey),
                                      ),
                                      child: Center(
                                          child: Text('Image ${num = index + 1}')),
                                    ))
                                : GestureDetector(
                                    child: Container(
                                        height: 40.0,
                                        width: 150.0,
                                        decoration: BoxDecoration(
                                          border: Border.all(color: Colors.grey),
                                        ),
                                        child: Image.file(
                                          File(_imageList[index].path),
                                          fit: BoxFit.cover,
                                        )));
                          }),
                    )),

在此处输入图像描述

在此处输入图像描述

You're loading 5 list of items.您正在加载 5 个项目列表。 Once you pick an image your imageList will not be empty and Once your imageList isn't empty, then it'll try to display list of images with indexes.一旦你选择了一个图像,你的 imageList 就不会为空,一旦你的 imageList 不为空,它就会尝试显示带有索引的图像列表。 Since you've picked 1 image in imageList and you can only display imageList[0].由于您在 imageList 中选择了 1 张图像,因此您只能显示 imageList[0]。 Since imageList[index] tries to access other indexes and you don't have items on those indexes, it'll throw Range Error.由于 imageList[index] 尝试访问其他索引并且您在这些索引上没有项目,因此它将引发 Range Error。

There are other ways of doing this but in my case, I'm doing this.还有其他方法可以做到这一点,但就我而言,我正在这样做。 Create an extension function on all iterable types globally in your code.在代码中全局为所有可迭代类型创建扩展 function。 Declare it outside main function or in a separate file.在主 function 之外或在单独的文件中声明它。 If the item at index exists, it'll return you the item else null.如果索引处的项目存在,它将返回项目否则为 null。

extension ItemAtIndexOrNull<T> on Iterable<T> {
  itemAtIndexOrNull(int index) {
try {
  final data = this.elementAt(index);
  return data;
} catch (e) {
  return null;
}

} } } }

And Now replace your _imageList?.isEmpty??现在替换你的 _imageList?.isEmpty?? true with _imageList.itemAtIndexOrNull(index) == null true with _imageList.itemAtIndexOrNull(index) == null

You have set the itemCount to 5, instead use a list of null.您已将 itemCount 设置为 5,而是使用 null 列表。 And you can check the item at an index is null or type of File.您可以检查索引处的项目是 null 或文件类型。 If its file then item is loaded else not.如果它的文件则加载项,否则不加载。

    import 'dart:io';
    import 'package:flutter/material.dart';
    import 'package:image_picker/image_picker.dart';
 
   class ListImages extends StatefulWidget {
     @override
     _ListImagesState createState() => _ListImagesState();
     }
    class _ListImagesState extends State<ListImages> {
      Future _getImage() async {
        final image = await ImagePicker().pickImage(source: ImageSource.gallery);
        setState(() {
          //_image = image;
          images.add(image!);
    
          //print('first element: ${_imageList!.isEmpty}');
          //print('second element: ${_imageList!.}');
        });
      }
    
      final List<XFile?> images = List<XFile?>.filled(5, null);
    
      @override
      Widget build(BuildContext context) {
        return ListView.separated(
          separatorBuilder: (context, index) => SizedBox(
            width: 5.0,
          ),
          scrollDirection: Axis.horizontal,
          itemCount: images.length,
          itemBuilder: (BuildContext context, int index) {
            XFile? file = images[index];
            return GestureDetector(
              onTap: file == null ? _getImage : null,
              child: Container(
                height: 40.0,
                width: 150.0,
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                ),
                child: file == null
                    ? Center(child: Text('Image ${index + 1}'))
                    : Image.file(
                        File(images[index]!.path),
                        fit: BoxFit.cover,
                      ),
              ),
            );
          },
        );
      }
    }
        

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM