【问题标题】:Adding image to ListTile in Flutter - specific issue在 Flutter 中将图像添加到 ListTile - 具体问题
【发布时间】:2020-11-11 11:03:32
【问题描述】:

所以我有这个非常规代码,我必须输入它以使列表图块内的容器具有使用 ImagePicker 选择的图像。这是sn-p:

File _smallImage;

ImagePicker 的函数如下:

 Future _getSmallImage() async {
PickedFile pickedFile = await picker.getImage(source: ImageSource.gallery);
setState(() {
  if (pickedFile != null) {
    _smallImage = File(_smallImage.path);
  } else {
    print('No image selected.');
  }
});

}

现在,这里有点令人困惑,这里是 ListTile 代码:

child: ListTile(
                  
                  trailing: Container(
                    height: 120.0,
                    width: 100.0,
                    //color: Colors.white,
                    decoration: BoxDecoration(
                      color: Colors.white,
                       FileImage(File(_smallImagepath)) : null
                      image: DecorationImage(
                        image: _smallImage == null
                            ? MemoryImage(kTransparentImage)
                            : FileImage(_smallImage),
                        fit: BoxFit.cover,
                         
                      ),
                    ),

                    child: IconButton(
                      
                      
                      icon: Icon(Icons.add),
                      file u path,
                     
                      onPressed: () => _getSmallImage(),
                    ),
                  ),

如您所见,ListTile 中有一个 IconButton(我必须这样做,因为列表图块也具有 onPressed 功能,这是小按钮和列表图块本身的唯一方法按下)。它具有获取图像的 _getSmallImage() ImagePicker 函数。在那里,有一个装饰图像,它采用了选择的图像:

image: DecorationImage(
                        image: _smallImage == null
                            ? MemoryImage(kTransparentImage)
                            : FileImage(_smallImage),
                        fit: BoxFit.cover,

但问题是,我收到“在 null 上调用”错误,但我不确定是什么原因造成的,因为在 null 的情况下我有一个三元:

The getter 'path' was called on null.

当我尝试从图库中选择图像时发生错误。我知道它有点长,但实际上并没有那么多代码,我只是想尽可能地解释这个问题。谢谢!

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您必须使用 pickedFile.path 而不是 _smallImage

    setState(() {
      if (pickedFile != null) {
        _smallImage = File(pickedFile.path); // Change this line.
      } else {
        print('No image selected.');
      }
    });
    

    【讨论】:

    • 好吧,当然,现在我觉得自己很愚蠢。非常感谢,有时最简单的解决方案会被忽略。
    猜你喜欢
    • 2021-02-22
    • 1970-01-01
    • 2021-06-08
    • 2021-10-06
    • 2020-06-22
    • 2021-10-07
    • 2013-03-29
    • 2023-04-01
    相关资源
    最近更新 更多