【问题标题】:How to get and update the current index of a widget in a list of widgets?如何获取和更新小部件列表中小部件的当前索引?
【发布时间】:2020-02-16 22:36:45
【问题描述】:

我正在构建一个小部件列表。我想在列表磁贴中显示小部件的索引。我该怎么做?它没有被显示,因为键是在运行时分配的,并且当前索引试图在小部件构建之前被初始化?如果是,我如何显示小部件索引?如果不是,那么发生了什么,我该如何显示索引?被困在这个问题上太久了,现在是新手。

  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',)
           )
      )
}

【问题讨论】:

  • data 中没有项目,因为它被初始化为一个空列表。还是我错过了什么?
  • 哦,我没有发布我单击按钮以从数据中添加或删除小部件的代码。最初列表是空的,但单击按钮会添加一个新的小部件。

标签: flutter


【解决方案1】:

您可以使用 widget.index。

在源码中,你可以通过widget.index访问list或者listView中的widget顺序,这个变量返回对应的widget值。

像这样:

 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;
      },
    );

【讨论】:

    猜你喜欢
    • 2020-11-21
    • 2020-01-23
    • 2014-01-21
    • 2018-05-26
    • 2022-11-04
    • 2021-11-18
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    相关资源
    最近更新 更多