【问题标题】:The getter 'docs' was called on null as QuerySnapshot is null even after it's initialised in initState()getter 'docs' 在 null 上调用,因为 QuerySnapshot 即使在 initState() 中初始化后也是 null
【发布时间】:2021-02-22 07:39:26
【问题描述】:

这是导致错误的代码: 还值得注意的是 print('mysnapshot.docs.length') 打印的长度很好,表明 mysnapshot 不为空 在初始化状态之后。但是,在小部件构建器块中,mysnapshot 的值为 null,原因我无法弄清楚。

我是 Flutter 的新手,我希望得到一个愚蠢的答案。这也是我对 Stackoverflow 的第一个问题。提前致谢。

class _PlayQuizState extends State<PlayQuiz> {
  DatabaseService serv = new DatabaseService();
  QuerySnapshot mysnapshot;


  @override
  void initState() {

    serv.getQuestionData(widget.quizID).then((value){mysnapshot=value; print(mysnapshot.docs.length);});
  

    print("${widget.quizID}");
    super.initState();
  }
  

  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: AppBar(title: Row(
      children: [
        SizedBox(width: MediaQuery.of(context).size.width/5.8,),
        appbar(context),
      ],
    ),backgroundColor: Colors.transparent,elevation: 0.0,iconTheme: IconThemeData(color: Colors.black54),),body:
   

          Text(mysnapshot.docs.length.toString()), // Mysnapshot is null, can't figure out why
      ],),),);
  }
}

【问题讨论】:

    标签: android firebase flutter dart google-cloud-firestore


    【解决方案1】:

    InitStatebuild 方法的启动非常接近,因此在 initState 中声明的新变量不会启动是正常的出现在您的构建方法中。您可以做的是使用 FutureBuilder 小部件,其中 future 参数将与 initState 中的声明完全相同;

    FutureBuilder<QuerySnapshot>(
                  future: serv.getQuestionData(widget.quizID),
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return CircularProgressIndicator();
                    }
                    return Text(snapshot.data);
                  },
                ),
    

    【讨论】:

    • 感谢您的快速回复,这似乎可以解决问题。赞成:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    相关资源
    最近更新 更多