Flutter: Why setState(( ) { }) set data again and again

前端 未结 1 979
鱼传尺愫
鱼传尺愫 2021-01-23 06:40

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?

Here is my

相关标签:
1条回答
  • 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.

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

    Example:

    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');
          }
        ),
      }
    }
    
    0 讨论(0)
提交回复
热议问题