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



以下是导致错误的代码:还值得注意的是,print('mysnapshot.docs.length'(打印长度fine,指示mysnapshot不为nullinitState之后。然而,在小部件构建器块中,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中声明的新变量不会出现在您的构建方法中是正常的。相反,您可以使用FutureBuilder小部件,其中它的future参数将与initState内的声明完全相同;

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

最新更新