【问题标题】:Remove Image from Widget's list从小部件列表中删除图像
【发布时间】:2020-06-12 03:44:29
【问题描述】:

在我的页面上,我有一个拍照按钮。拍完这张照片后,它会更新我的模型(它使用 Provider ChangeNotifier)。拍完照片后,页面就会重建,并且在 Scaffold 主目录中我正在构建小部件:

Widget build(BuildContext context) {
  return SingleChildScrollView(
    // Somewhere in the middle of this
    getPicturesSection(),
    // Continue with other widgets
  )
}

Widget getPicturesSection(BuildContext context) {
  var imagesPath = Provider.of<MyModel>(context, listen:false).imagesPath;
  var wids = <Widget>[]

  // Basically show all the taken pictures
  imagesPath.forEach((f) {
      wids.add(
          Image.file(
              File(f)
          )
      )
  })

  return Row(children: wids);
}

我想要做的是允许用户删除每个图像。所以我想在每张图片下方添加一个删除图标:

imagesPath.forEach((f) {
    wids.add(
        Column(
            children: <Widget> [
                Image.file(
                    File(f)
                ),
                IconButton(
                    onTap: () {
                        // How do I delete from the very same list that I am using to build this list?
                    }
                ),
            ],
        )
    )
})

没关系,我想出了答案。由于我已经在使用 ChangeNotifier,我只需要添加从模型中删除条目的函数,并且更改将向下传播。

List<String> imagesPath = new List<String>();
removeRejectionPicturePath(int ind) {
  this.imagesPath.removeAt(ind);
  notifyListeners();    // This will basically ask all the widgets that is the listener to rebuild the widget tree
}

【问题讨论】:

    标签: flutter


    【解决方案1】:

    你可以试试这个!

    imagesPath.forEach((f) {
        wids.add(
            Column(
                children: <Widget> [
                    Image.file(
                        File(f)
                    ),
                    IconButton(
                      icon:Icon(Icons.remove_circle),
                        onPressed: () {
                           setState((){
                             wids.removeAt(imagesPath.values.toList().indexOf(f));
                           });                       
                        }
                    ),
                ],
            )
        );
    });
    

    【讨论】:

    • 抱歉,我的代码可能不清楚。我对其进行了编辑以使其更清晰。对局部变量调用 setState 不会使树重建,所以这不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多