【问题标题】:setState reloads old value after value changesetState 在值更改后重新加载旧值
【发布时间】:2021-04-03 15:26:55
【问题描述】:

我有一个颤振的问题: 这是我从 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');
    }

【问题讨论】:

    标签: android flutter dart setstate


    【解决方案1】:

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

    不要等待响应:

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

    【讨论】:

    • 还是一样,重新加载旧值,然后加载新值
    • 你能告诉我你是怎么打电话给SendValues的吗?
    • ` RaisedButton( splashColor: Theme .of(context) .primaryColor, highlightColor: Theme .of(context) .primaryColor, color: Colors.blueAccent, child: Text( 'Save', style: TextStyle (fontWeight: FontWeight.bold, color: Colors.white, fontSize: 20),), onPressed: () { SendValues(photos.first.id); }), `
    • 您没有使用来自SendValues 的返回值,请确保您的FutureBuilder 使用它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 2015-01-14
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多