【问题标题】:How to return a widget if it is the last index of a list?如果它是列表的最后一个索引,如何返回一个小部件?
【发布时间】:2020-12-03 12:25:03
【问题描述】:

如果小部件是方法中的最后一项,我想重新调整它 但我收到一个错误...尝试调用:call()

 itemList.last()
     ? CircleAvatar(
       backgroundColor: mainColor,
       radius: 15,
       child: Icon(Icons.done),
        )
      : Container()

【问题讨论】:

    标签: list flutter dart lastindexof


    【解决方案1】:

    假设您使用的是ListView.builder()

    class _MyAppState extends State<MyApp> {
      @override
      Widget build(BuildContext context) {
        List<String> item = [
          'jan',
          'feb',
          'mar',
          'apr',
          'may',
          'jun',
          'jul',
          'aug',
          'sep',
          'oct',
          'nov',
          'dec'
        ];
        return Scaffold(
          body: ListView.builder(
            itemCount: item.length,
            itemBuilder: (context, index) {
              if (index == item.length - 1) {
                return ListTile(
                  leading: Text('Last index reached'),
                );
              }
              return ListTile(
                leading: Text(item[index]),
              );
            },
          ),
        );
      }
    }
    

    【讨论】:

    【解决方案2】:

    你的问题太模糊了。 我会假设你正在一个列表上循环,并希望在涉及到最后一个元素时显示一个特定的小部件。

    所以你所要做的就是检查你所在的索引是否等于列表的长度-1

    for (int i=0;i<myList.length;i++) {
        if (i == myList.length -1) {
             return CircleAvatar(
                 backgroundColor: mainColor,
                 radius: 15,
                 child: Icon(Icons.done),
             );
        } else {
              return Container();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-10
      • 2011-12-14
      • 2017-05-11
      • 1970-01-01
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多