【问题标题】:Using initState to get values from functions and insert into variable before Build在构建之前使用 initState 从函数中获取值并插入到变量中
【发布时间】:2021-04-26 09:25:45
【问题描述】:

我有两个函数试图从中获取值,并将其存储到 main_page 中的变量中,以便我可以在构建小部件中使用。我正在使用 firebase 实时数据库。
我拥有的功能是:

Future<List> receive_button(String button) async{
    List<String> lst = new List<String>(2);

    final FirebaseUser user = await _auth.currentUser();
    var snapshot = await databaseReference.child(user.uid+"/buttons/"+button+"/icon").once();
    String result = snapshot.value;

    var snapshot1 = await databaseReference.child(user.uid+"/buttons/"+button+"/nome").once();
    String result1 = snapshot1.value;
    
    lst[0] = result;
    lst[1] = result1;

    print(lst);
    return lst;
  }

  Future<int>  receive_quantity() async{
    final FirebaseUser user = await _auth.currentUser();
    var snapshot = await databaseReference.child(user.uid+"/buttons/quantity").once();
    var result = snapshot.value;
    print(result);
    return result;
  }

这就是我尝试将数据存储在 home_page 的变量中的方式:

class _HomeState extends State<Home> {

  int quantity = 0;
  List<String> lst = new List<String>(2);

  final AuthService _auth = AuthService();
  
  @override
  void initState() {
    super.initState();
    _auth.receive_quantity().then((value) => quantity = value);
    _auth.receive_button("button1").then((value) => lst = value);
  }

但每当我尝试在 Widget 构建中打印值时,我都会得到以下信息:

flutter: 0
flutter: [null, null]

在我的数据库中这个flutter: 0,实际值为2。
而这个flutter: [null, null]has ["add", "Chocolate"]
我已经测试了函数本身,它为我提供了正确的数据,但我在仅存储它们时遇到了问题。

【问题讨论】:

    标签: flutter dart firebase-realtime-database flutter-layout flutter-dependencies


    【解决方案1】:

    试试这个,因为我知道你不能在覆盖方法initState() 中使用等待,所以这是我通常做的,它工作正常

    @override
      void initState() {
        super.initState();
        asyncInit();
      }
    
    void asyncInit() async {
       quantity = await _auth.receive_quantity();
       lst = await _auth.receive_button("button1");
       setState(() {});
    }
    

    【讨论】:

    • 但是你需要调用 setState 因为这些是局部变量,我已经编辑了 asyncInit()。
    • 这实际上工作得很好,你能看看这篇文章并尝试帮助我吗:stackoverflow.com/questions/65819570/…
    【解决方案2】:

    你可以使用futurebuilder

    FutureBuilder(
      future: Future.wait([receive_button, receive_quantity]), //Init receive_button/quantity in initState
      builder: (context, AsyncSnapshot<List<dynamic>> snapshot) {
        if (snapshot.hasData) { //Wait for futures to finish
            int quantity = snapshot.data[1];
            List<String> lst = snapshot.data[0];
            return Container(...);
        else {
            return Text("Waiting for datas...");
        }
      },
    );
    

    【讨论】:

      猜你喜欢
      • 2015-03-26
      • 2023-02-14
      • 2014-03-24
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      相关资源
      最近更新 更多