首页 > 解决方案 > InitState - 函数未在 Flutter 上执行

问题描述

我正在通过 initState 调用以下函数,但由于某种原因它没有运行,当我打印一些“测试”时,控制台上没有出现任何内容。有什么问题?(我的州内还有其他功能)

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home>
    with AutomaticKeepAliveClientMixin<Home> {
  @override
  void initState() {
    super.initState();
    getInfo();
  }


  int countPost = 0;
  List<Post> contentList = [];


getInfo() async {
    QuerySnapshot querySnapshot = await contentReference
        .document(_id)
        .collection("usersContent")
        .getDocuments();

    setState(() {
      countPost = querySnapshot.documents.length;
      contentList = querySnapshot.documents
          .map((documentSnapshot) => Post.fromDocument(documentSnapshot))
          .toList();
    });
    print("Test");
  }
}

标签: flutter

解决方案


首先,你不应该在 initState 中调用 setState,也可能 querySnapshot 有一些错误,做一个 try-catch 块来看看发生了什么。

getInfo() async {
    print("init state is started");
    try{
      QuerySnapshot querySnapshot = await contentReference
          .document(_id)
          .collection("usersContent")
          .getDocuments();

      setState(() {
        countPost = querySnapshot.documents.length;
        contentList = querySnapshot.documents
            .map((documentSnapshot) => Post.fromDocument(documentSnapshot))
            .toList();
      });}
      catch(e){
      print('error is $e')
      }
      print("Test");
    }

编辑:更好的实现是使用 FutureBuilder:

import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State < Home > with AutomaticKeepAliveClientMixin {
  int countPost = 0;
  List < Post > contentList = [];
 Future getInfo() async {
    print("FutureBuilder is started");
    try {
      QuerySnapshot querySnapshot = await contentReference
          .document(_id)
          .collection("usersContent")
          .getDocuments();

      countPost = querySnapshot.documents.length;
     return contentList = querySnapshot.documents
          .map((documentSnapshot) => Post.fromDocument(documentSnapshot))
          .toList();
    } catch (e) {
      return print('error is $e');
    }
  }
  @override
  bool get wantKeepAlive => true;
  Widget build(BuildContext context) {
    super.build(context);

    return FutureBuilder(
        future: getInfo(),
        builder: (context, AsyncSnapshot snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: CircularProgressIndicator(
                strokeWidth: 6,
                valueColor:
                AlwaysStoppedAnimation < Color > (Colors.redAccent),
              ),
            );
          } else {
            return Text('Done', style: TextStyle(color: Colors.black, fontSize: 40), );
          }
        }
    );
  }
}

推荐阅读