首页 > 解决方案 > 在 Flutter 的磁贴中有条件地显示/隐藏复选框

问题描述

我有一个从 API 调用动态生成的图块列表。我在 AppBar 中有一个共享按钮,当我单击该按钮时,我想让复选框显示为列表图块中的尾随属性。例子:

ListTile(
  title: Text('fetchedData.title'),
  trailing: Checkbox()
)

我的方法是有条件地渲染图块,但我不确定我是否在正确的位置进行渲染。我正在使用布尔状态来确定复选框是否应显示在磁贴旁边。

我尝试过的其他方法是创建帮助函数来为我构建列表图块,但不确定它应该返回什么,如果您对如何制作这些排序函数有任何提示,请包括在内!

这是我的代码:

body: Center(
        child: FutureBuilder(
          future: pdfSnippets(),
          builder: (BuildContext context, AsyncSnapshot<List> snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                // will have to hide the eccess snippet with overflow
                //  and have a max width to fit the trailing checkbox
                itemCount: snippets.length,
                itemBuilder: (BuildContext context, int index) {
                  // if you don't like card view, remove Card and just return ListTile
                  return checkboxStatus ? 
                  Card (
                    child: ListTile(
                      // not referencing properly
                      title: Text('${snapshot[index].body}'),
                      subtitle: Text('${snapshot[index].title}'),
                      trailing: Checkbox(
                        value: false,
                      )
                    )
                  ) : 
                  Card (  
                    child: ListTile(
                    // not referencing properly
                    title: Text('${snapshot[index].body}'),
                    subtitle: Text('${snapshot[index].title}'),
                    onLongPress: () => setCheckboxStatus(),
                    )
                  );
                }
              );
            } else {
              throw('nothing to see here');
            }
          },
        ),
      ),

标签: flutterdartflutter-layout

解决方案


您可以CheckBox像这样制作条件以使您的代码看起来更简单:

ListTile(
// not referencing properly
title: Text('body'),
subtitle: Text('title'),
trailing: checkboxStatus
    ? Checkbox(
        value: false,
      )
    : null,
)

推荐阅读