【问题标题】:Camera image not being added to an image list in flutter相机图像未在颤动中添加到图像列表中
【发布时间】:2021-08-27 10:34:46
【问题描述】:

我在我的 Flutter 应用中使用 image_picker。

拍完照片后,我将其添加到 XFile 列表中。但是在检查列表长度时,它显示为 null。

当我遵循首先从图库添加图像然后从相机添加图像的路线时,它似乎工作正常。将相机图像添加到列表的正确方法是什么。我的代码如下:

List<XFile> ? _imageFileList;
List<XFile> ? pickedFile;
XFile ? file;


void getImageFile(ImageSource source, bool multimage) async {

if(multimage) {

  pickedFile = await _picker.pickMultiImage(maxWidth: double.infinity,
      maxHeight: double.infinity, imageQuality: 10);

  setState(() {

    _imageFileList = pickedFile;
    print('image selected');
    Navigator.of(context).pop();

    Flushbar(

      message:  'length of imagelist ${_imageFileList?.length}',
      duration:  Duration(seconds: 5),
    )..show(context);

  });


} else{


 file = await _picker.pickImage(
  source: source, maxWidth: double.infinity,
  maxHeight: double.infinity, imageQuality: 10);

 setState(() {

 pickedFile?.add(file!) ;

 _imageFileList?.add(file!) ; //

 print('camera image selected');
 print('image selected');
 Navigator.of(context).pop();

 Flushbar(
   message:  'length of imagelist ${_imageFileList?.length}',
   duration:  Duration(seconds: 5),
 )..show(context);



 });



 }

【问题讨论】:

    标签: flutter dart imagepicker


    【解决方案1】:

    因为在 'else' 块中你没有初始化 _imageFileList。您正在尝试将项目添加到未初始化的列表中。因此,您可以在图库之后添加来自相机的图像。因为在'if'块中它会被初始化。

    有两种选择:

    1. List&lt;XFile&gt; _imageFileList = &lt;XFile&gt;[]; 并在“if”块中:_imageFileList.addAll(pickedFile) 而不是 _imageFileList = pickedFile;
    2. 在“其他”块中:if(_imageFileList == null) _imageFileList = &lt;XFile&gt;[]
      在“if”块中:if(_imageFileList == null) _imageFileList = &lt;XFile&gt;[] 之后,_imageFileList.addAll(pickedFile)

    对我来说,选项 1 是最好的方法。

    【讨论】:

    • 谢谢,会试一试,但问题不在于多图像选择。它在相机源上。
    • 没错,因为在 multiImage 中,您正在初始化列表。如果您在 multiImage 之前尝试相机源,则您有一个未初始化的列表,并且您无法将项目添加到未初始化的列表中。这就是它为空的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 2021-06-22
    相关资源
    最近更新 更多