如何同时使用FutureBuilder和setState方法?

时间:2020-08-22 08:01:06

标签: flutter

我试图通过使用FutureBuilder这样的代码从数据库中加载数据。

// counter application

import 'package:flutter/material.dart';

class SetStateScreen extends StatefulWidget {
  @override
  _SetStateScreenState createState() => _SetStateScreenState();
}

class _SetStateScreenState extends State<SetStateScreen> {
  Future<int> getData() async {
    int initNumFromDB = 0; // fetch some asynchronous initial value
    return initNumFromDB;
  }

  @override
  Widget build(BuildContext context) {
    int counter;
    return Container(
      color: Colors.white,
      child: FutureBuilder(
          future: getData(),
          builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
            Widget childWidget;
            if (snapshot.hasData) {
              counter = snapshot.data; 
              childWidget = Center(
                child: Container(
                    child: FlatButton(
                  onPressed: () {
                    setState(() {
                      counter += 1;
                    });
                  },
                  child: Text("$counter"),
                )),
              );
            } else {
              childWidget = Container();
            }
            return childWidget;
          }),
    );
  }
}

但是,当按下按钮并运行setState方法时,FutureBuilder会再次加载初始数据并重置计数器编号。如何一次加载初始数据并正确运行此代码?

2 个答案:

答案 0 :(得分:0)

尝试使用这是正确的使用方式

class SetStateScreen extends StatefulWidget {
  @override
  _SetStateScreenState createState() => _SetStateScreenState();
}

class _SetStateScreenState extends State<SetStateScreen> {
    Future<int> getData() async {
        int initNumFromDB = 0; // fetch some asynchronous initial value
        return initNumFromDB;
    }

    @override
    void initState() {
        super.initState();
        getData(); 
    }
}

答案 1 :(得分:-1)

您需要在initstate方法中调用future方法。这样,它将仅在构建窗口小部件时运行一次,而不在每次调用setstate()时运行。