首页 > 解决方案 > setState 在值更改后重新加载旧值

问题描述

我遇到了颤动的问题:这是我从 DB 填充 TextFields 的构建方法和用于将编辑后的值发送到 DB 的 SendValue 方法。在 setState TextFields 显示旧值一秒钟后,然后加载编辑后的值。这发生在服务器回答值已更改之后。重新加载旧值的原因是什么?

return Scaffold(
        appBar: AppBar(
          title: Text('Editing values'),
        ),
        body: Padding(
          child: FutureBuilder<List<Photo>>(
            future: fetchPhotos(http.Client(), args.id),
            builder: (context, snapshot) {

              if (snapshot.hasError) print(snapshot.error);

              return snapshot.hasData
                  ? Fields(snapshot.data)
                  : Center(child: CircularProgressIndicator());
            },
          ),
          padding: EdgeInsets.fromLTRB(30, 30, 30, 30),
        ),
      );


Future SendValues(String id) async {

      http.Client client;
      client = http.Client();
      var uri = new Uri.http('localhost', 'edituser.php');
      final response =
      await client.post(uri, body: {

        'id': id,
        'name': contname.text,
        'surname': contsurname.text,

      },
        );

      if  (response.body.contains('OK')) 

       setState(() {
       });
       else 
       print('error');
    }

标签: androidflutterdartsetstate

解决方案


它显示旧值,因为setState在 http 请求完成后被调用,这需要一段时间。

不要等待响应:

Future SendValues(String id) async {
  http.Client client;
  client = http.Client();
  var uri = new Uri.http('localhost', 'edituser.php');
  final response = client.post(
    uri,
    body: {'id': id, 'name': contname.text, 'surname': contsurname.text},
  );

  setState(() {});
  return response;
}

推荐阅读