您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何获取列表Flutter中所选项目的索引/键?

如何获取列表Flutter中所选项目的索引/键?

您可能希望ListTile在内构建的列表ListView,并使用List.generate构造函数获取的索引,children这是一个简单的示例:

在此处输入图片说明

import "package:Flutter/material.dart";

class ListTest extends StatefulWidget {
  @override
  _ListTestState createState() => new _ListTestState();
}

class _ListTestState extends State<ListTest> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  int _id;
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: _scaffoldKey,
      appBar: new AppBar(title: new Text("List"),),
      body: new ListView(
          children: new List.generate(10, (int index){
            return new ListTile(title: new Text("item#$index"),
            onTap:(){
              setState((){
                _id = index; //if you want to assign the index somewhere to check
              });
              _scaffoldKey.currentState.showSnackBar(new SnackBar(content: new Text("You clicked item number $_id")));
            },
            );
          })

      ),
    );
  }
}

请记住,这种方法List.generate在小列表上也能很好地工作,如果您正在阅读可扩展列表(例如,用户列表),则需要使用ListView.builder而不是一个ListView带有builder参数的参数,该参数也允许您按索引遍历列表。

new ListView.builder(itemBuilder: (BuildContext context, int index) {
        //return your list
      },
其他 2022/1/1 18:14:13 有597人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶