簡體   English   中英

獲取在 flutter 的列表視圖中工作的圖像

[英]Get images working in a listview in flutter

我在使用 imagePicker 獲取圖像以在列表視圖中工作時遇到問題。 當您按下列表視圖中的一個容器時,您應該能夠從圖庫中選擇一個圖像。 這第一次有效,但后來我得到一個 RangeError (index) Invalid value: Only valid value 0: 1 on the rest of the box(見下圖)。 正如你所看到的,我試圖使用索引來檢查元素是否有任何數據,但我認為我沒有做對。 請提供任何建議的代碼示例!

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,
                                        )));
                          }),
                    )),

在此處輸入圖像描述

在此處輸入圖像描述

您正在加載 5 個項目列表。 一旦你選擇了一個圖像,你的 imageList 就不會為空,一旦你的 imageList 不為空,它就會嘗試顯示帶有索引的圖像列表。 由於您在 imageList 中選擇了 1 張圖像,因此您只能顯示 imageList[0]。 由於 imageList[index] 嘗試訪問其他索引並且您在這些索引上沒有項目,因此它將引發 Range Error。

還有其他方法可以做到這一點,但就我而言,我正在這樣做。 在代碼中全局為所有可迭代類型創建擴展 function。 在主 function 之外或在單獨的文件中聲明它。 如果索引處的項目存在,它將返回項目否則為 null。

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

} }

現在替換你的 _imageList?.isEmpty?? true with _imageList.itemAtIndexOrNull(index) == null

您已將 itemCount 設置為 5,而是使用 null 列表。 您可以檢查索引處的項目是 null 或文件類型。 如果它的文件則加載項,否則不加載。

    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