Flutter 如何获取和更新小部件列表中小部件的当前索引?

Flutter 如何获取和更新小部件列表中小部件的当前索引?,flutter,Flutter,我正在建立一个小部件列表。我想在列表平铺中显示小部件的索引。我该怎么做呢?是不是因为键是在运行时分配的,而当前索引是在小部件构建之前尝试初始化的,所以没有显示它?如果是,如何显示小部件索引?如果没有,那么发生了什么,我如何显示索引?在这个问题上停留的时间太长了,现在还不熟悉 final GlobalKey<AnimatedListState> _listKey = GlobalKey(); List<Widget> _data = []; Widget Su

我正在建立一个小部件列表。我想在列表平铺中显示小部件的索引。我该怎么做呢?是不是因为键是在运行时分配的,而当前索引是在小部件构建之前尝试初始化的,所以没有显示它?如果是,如何显示小部件索引?如果没有,那么发生了什么,我如何显示索引?在这个问题上停留的时间太长了,现在还不熟悉

  final GlobalKey<AnimatedListState> _listKey = GlobalKey();
  List<Widget> _data = [];

  Widget SubActivitiesListTiles() {
    SizeConfig().init(context);
    return Container(
      child: Container(
        child: AnimatedList(
            shrinkWrap: true,
            key: _listKey,
            initialItemCount: _data.length,
            itemBuilder: (context, index, animation) {
              return _buildItem(_data[index], animation);
            }),
      ),
    );

  Widget _buildItem(CustomListTile, Animation animation) {
    return SizeTransition(
      sizeFactor: animation,
      child: Card(
        shape: Border(bottom: BorderSide(width: 0.4, color: Colors.black12)),
        elevation: 0,
        child: CustomListTile,
      ),
    );
  }
Widget ActivityTile(context, obj) {
    int currentIndex=_data.indexWhere((item) =>(item.key == uniqueKey));;
    UniqueKey uniqueKey = new UniqueKey();

    return Container(
      key: uniqueKey,
        color: Colors.white,
        child: ListTile(
            onTap: () {
              setState(() {
                currentIndex =
                    _data.indexWhere((item) =>(item.key == uniqueKey));
                Index;
                updateTile(currentIndex);
              });
            },
            title: Text(
              '$currentIndex',)
           )
      )
}

final GlobalKey _listKey=GlobalKey();
列表_data=[];
小部件子活动ListTiles(){
SizeConfig().init(上下文);
返回容器(
子:容器(
子:动画列表(
收缩膜:对,
键:_listKey,
initialItemCount:_data.length,
itemBuilder:(上下文、索引、动画){
返回_buildItem(_数据[索引],动画);
}),
),
);
Widget\u buildItem(CustomListTile、动画){
返回大小转换(
sizeFactor:动画,
孩子:卡片(
形状:边框(底部:边框边(宽度:0.4,颜色:Colors.black12)),
海拔:0,
child:CustomListTile,
),
);
}
Widget ActivityTile(上下文,obj){
int currentIndex=_data.indexWhere((item)=>(item.key==uniqueKey));;
UniqueKey UniqueKey=新的UniqueKey();
返回容器(
键:唯一键,
颜色:颜色,白色,
孩子:ListTile(
onTap:(){
设置状态(){
当前索引=
_data.indexWhere((item)=>(item.key==uniqueKey));
指数
更新文件(当前索引);
});
},
标题:正文(
“$currentIndex”,)
)
)
}

您可以使用widget.index

在源代码中,您可以使用widget.index访问列表或listView中的小部件顺序,其中该变量返回相应的小部件值

像这样:

 return TextFormField(
      controller: _nameController,
      onChanged: (v) => _MyFormState.friendsList[widget.index] = v,
      decoration: InputDecoration(
        hintText: 'enter index number'
      ),
      validator: (v){
        if(v.trim().isEmpty) return 'enter the value';
        return null;
      },
    );

data
中没有项目,因为它被初始化为空列表。或者我遗漏了什么?哦,我没有在单击按钮添加或从数据中删除小部件的位置发布代码。最初列表是空的,但单击按钮后会添加新的小部件。