繁体   English   中英

getter 'docs' 在 null 上被调用,因为即使在 initState() 中初始化 QuerySnapshot 也是 null

[英]The getter 'docs' was called on null as QuerySnapshot is null even after it's initialised in initState()

这是我导致错误的代码: 还值得注意的是 print('mysnapshot.docs.length') 打印长度很好,表明 mysnapshot 在 initState 之后不为空。 但是,在小部件构建器块中,由于我无法弄清楚的原因,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
      ],),),);
  }
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM