首页 > 解决方案 > 发回数据后列表视图不会更新(颤振)

问题描述

由于我是 Flutter 的新手,我为多个问题道歉。

我正在尝试从颤动的路线发回数据(列表项索引)以从 ListView 中删除。但是,ListView 没有更新。不知道我在这里做错了什么。我已经缩短了一些代码,但是如果您需要更多代码,请告诉我。我感谢您的帮助。

  List clients;

  Appointments({Key key, @required this.clients}): super(key: key);

  @override
  State<StatefulWidget> createState() {
    return AppointmentState();
  }
}

class AppointmentState extends State<Appointments> {
  @override
  Widget build (BuildContext context) {
    return Container(
      child: Expanded(
        child: ListView.builder(
          itemCount: widget.clients.length,
          itemBuilder: (context, index) {
            var client = widget.clients[index];

            return Dismissible(
              key: Key(client),
              direction:DismissDirection.endToStart,
              onDismissed: (direction) {
                setState () {
                  widget.clients.removeAt(index);
                }
              },
              background: Container(color: Colors.red),
              child: ListTile(
                title: Text(client),
                leading: Icon(Icons.face),
                trailing: Icon(Icons.keyboard_arrow_right),
                onTap: () {
                  //list index, and index data (client)
                  _checkIfRemoved(context, index, client);
                }
              ),
            );...

_checkIfRemoved 方法:

void _checkIfRemoved (BuildContext context, index, client) async {
    final result = await Navigator.push(context, MaterialPageRoute(builder: (context) => Client(clientIndex: index, clientName: client)));
    setState() {
      widget.clients.removeAt(result);
    }
    print(result);
  }

客户端画面

RaisedButton(
              child: Text("Remove Client"),
              color: Colors.red,
              onPressed: () {
                Navigator.pop(context, widget.clientIndex);
              },
            )

标签: flutterdart

解决方案


setState您使用的不正确

改变这个:

 setState() {
      widget.clients.removeAt(result);
    }

对此:

    setState(() {
       widget.clients.removeAt(result);
    });

推荐阅读