有条件地在 Flutter 中显示/隐藏图块中的复选框

时间:2020-12-30 00:25:44

标签: flutter dart flutter-layout

我有一个从 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');
            }
          },
        ),
      ),

1 个答案:

答案 0 :(得分:1)

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

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