Flutter:为什么setState((){})一次又一次地设置数据 [英] Flutter: Why setState(( ) { }) set data again and again

查看:101
本文介绍了Flutter:为什么setState((){})一次又一次地设置数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 setState((){})为变量分配值.但是它一次又一次地打印.为什么会这样反应?我该如何解决?

I use setState(() {}) for assigning a value to a variable. But it's printing again and again. Why does it react like this? And how can I fix it?

这是我的代码:

class Sample extends StatefulWidget {
  @override
  _SampleState createState() => _SampleState();
}

class _SampleState extends State<Sample> {
  String _message;
  String _appLink;
  Firestore db = Firestore.instance;
  @override
  Widget build(BuildContext context) {
    db.collection('share').document('0').get().then((value) {
      var message = value.data['message'];
      print(message);
      var appLink = value.data['appLink'];
      setState(() {
        _message = message;
        _appLink = appLink;
      });
    });
    return Container(
      child: Text('$_message $_appLink'),
    );
  }
}

这是我的输出:

此处 _appLink 的值为 www.facebook.com

推荐答案

setState 的目的是告诉框架状态中的变量已更改,并且需要重建小部件以反映那改变.因此,调用 setState 会再次调用 build 函数,在您的情况下,该函数会调用您的 Future ,该函数会再次调用 setState ,会触发 build 等.

The purpose of setState is to tell the framework that a variable in the state has changed and the widget needs to be rebuilt to reflect that change. So calling setState calls the build function again, which in your case recalls your Future, which calls setState again, which triggers build and so on.

要解决此问题,您应该在 initState 中调用 Future ,并在就绪后使用 FutureBuilder 显示数据.

To fix this you should call the Future in initState, and use a FutureBuilder to display the data when it's ready.

示例:

class _SampleState extends State<Sample> {
  Firestore db = Firestore.instance;
  Future databaseFuture;

  @override
  void initState() {
    databaseFuture = db.collection('share').document('0').get()
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: databaseFuture,
      builder: (context, snapshot) {
        if(!snapshot.hasData) {
          return CircularProgressIndicator();
        }
        var message = snapshot.data.data['message'];
        print(message);
        var appLink = snapshot.data.data['appLink'];
        return Text('$message $appLink');
      }
    ),
  }
}

这篇关于Flutter:为什么setState((){})一次又一次地设置数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆