【问题标题】:Flutter / Dart: How to add an extra widget at the bottom of a ListView?Flutter / Dart:如何在 ListView 底部添加一个额外的小部件?
【发布时间】:2021-11-25 17:56:59
【问题描述】:

我需要在列表视图的末尾添加一个文本小部件。 我根据我的需要想出了这个代码 sn-p 。此代码基于thisthis 代码。

此代码的问题是,它不可滚动。我该如何解决这个问题?将小部件添加到 ListView 末尾的最佳方法是什么?

    List<Widget> listItems = [];
    int listItemCount = 0;
    listItems.addAll(snapshot.data!.docs.map((DocumentSnapshot document) {
      Map<String, dynamic> data = document.data()! as Map<String, dynamic>;
      if (data['status'] == true) {
        listItemCount++;
        return ListTile(
          title: Text(data['full_name']),
          subtitle: Text(data['company']),
        );
      } else {
        return SizedBox();
      }
    }).toList());

    return ListView(children: <Widget>[
      ListView(
        shrinkWrap: true,
        children: listItems,
      ),
      (listItemCount > 0) ? Text('All Finish') : Text('Not available'),
    ]);

【问题讨论】:

    标签: firebase flutter listview


    【解决方案1】:

    使用 ListView.separated

    ListView.separated(
         itemCount: listItems.length,
         separatorBuilder: (BuildContext context, int index) {
           if(index == ListItems.length-1){
             return Container(height: 50, color: Colors.red);
           }
           else {
             return SizedBox();
           }
         },
         itemBuilder: (BuildContext context, int index) {
    

    【讨论】:

    • 这对我有用,谢谢。但只有在将 if 行更改为 index==ListItems.length-2 之后。尽管如此,还是想了解它为什么会发生?
    【解决方案2】:

    为什么不在listItems 的末尾添加一个磁贴?像这样的:

    ...
    const finalTile = ListTile(
      title: Text((listItemCount > 0) ? Text('All Finish') : Text('Not available')),
    );
    listItems.add(finalTile)
    
    return ListView(children: <Widget>[
      ListView(
        shrinkWrap: true,
        children: listItems,
      ),
      ,
    ]);
    

    【讨论】:

    • 感谢您的回复!我已经试过了。我实际上不能这样做,因为对于每个listItemCount++;,小部件都会尝试重建。这不是实际的代码,这在结构上与我正在处理的代码相似。
    【解决方案3】:

    很简单..检查这个代码sn-p

    return ListView.builder
      (
        itemCount: listItems.length + 1, // here is the trick, we are adding +1 for extra widget at bottom
        itemBuilder: (BuildContext ctxt, int index) {
         if (index < listItems.size - 1)
              return new Text("List Item");
         else
            return new Text("Last Extra widget"); // This will be the extra widget at last
        }
      )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-10
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 2019-11-09
      • 2020-11-26
      • 1970-01-01
      相关资源
      最近更新 更多