Flutter:按下OnTapped时如何更改状态

bgibtngc  于 2023-10-22  发布在  Flutter
关注(0)|答案(2)|浏览(152)

我想改变我点击后的颜色和轨迹图标.问题是图标和thrail不改变后,我点击索引.下面是我代码:

Widget _builduserlist(BuildContext context, List<postmodel> model) {
    List<bool> itemTappedState = List.generate(model.length, (index) => false);
  
  return  Center(
      child: ListView.builder(
        itemCount: model.length,
        itemBuilder: (context, index) {
          return Card(
            
            color: itemTappedState[index]
                ? Colors.blue // Change the color when tapped
                : Colors.green,
            child: ListTile(
              title: Text('${model[index].id}'),
              subtitle: Text('${model[index].dateofinsp}'),
              leading: const Icon(Icons.edit_road),
              trailing: itemTappedState[index]
                  ? const Icon(Icons.check)
                  : const Icon(Icons.warning), // Change the trailing icon when tapped
              onTap: () {
                print(itemTappedState[index].toString());
                setState(() {
                  itemTappedState[index] = !itemTappedState[index];
                  print(itemTappedState[index].toString());
                });
                
                _showConfirmationDialog(context, model[index]);
                
              },
            ),
          );
        },
      ),
    );
}

我在setState()和setState()中打印了bool。它在setState()中改变,但在索引中不变。如何解决这个问题

3okqufwl

3okqufwl1#

问题是itemTappedState是在_builduserlist方法中声明的:

Widget _builduserlist(BuildContext context, List<postmodel> model) {
    List<bool> itemTappedState = List.generate(model.length, (index) => false);
...
}

_builduserlist方法在每个setState都重新运行。因此,itemTappedState将重置为您每次更新UI时设置的值。
要解决这个问题,请将itemTappedState移动到State类中:

List<bool> itemTappedState = List.generate(model.length, (index) => false);
Widget _builduserlist(BuildContext context, List<postmodel> model) {
...
}
zour9fqk

zour9fqk2#

setStateStatefulWidgetState内部工作。所以你应该像这样制作你的用户列表小部件:

class _UserList extends StatefulWidget {
  const _UserList(this.model);

  final List<postmodel> model;

  @override
  State<_UserList> createState() => _UserListState();
}

class _UserListState extends State<_UserList> {
  List<bool> itemTappedState = List.generate(model.length, (index) => false);

  @override
  Widget build(BuildContext context) {
    return Center(
      // ...
    );
  }
}

**注意:**将此代码放在顶层(在任何其他类之外)

相关问题