我正在尝试从 firestore 显示用户的爱好列表,我从那里获取值,因为它在控制台中打印但无法显示。
错误:-
The getter 'hobbies' was called on null.
Receiver: null
Tried calling: hobbies
创建账户数据是模型类:-
Future<CreateAccountData> getUser() async {
final User user = auth.currentUser;
return _reference.doc(user.uid).get().then((m) => CreateAccountData.fromDocument(m));
}
以这种方式获取数据并在控制台中打印出来:-
List hobbies;
void initState() {
super.initState();
getUser().then((value) {
if (!mounted) return;
setState(() {
accountData = value;
hobbies = value.hobbies;
print("hobbies"+ hobbies.toString());
});
});
}
错误将我带到我评论的那一行:-
child:GridView.builder(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: accountData.hobbies.length, // Error take me to hobbies.
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 5, crossAxisSpacing: 5,),
itemBuilder: (BuildContext context, int index){
return Padding(
padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
child: Text(accountData.hobbies[index]),
);
}
),
关于更新到此的建议(包含在未来的构建器中):-
child: FutureBuilder(
future: getUser(),
builder: (context, snapshot){
if(snapshot.connectionState == ConnectionState.waiting){
return Center(
child: CircularProgressIndicator(),
);
} if(snapshot.data.docs.isEmpty){
return Align(
alignment: FractionalOffset.centerLeft,
child: Text("Add what you love to do.....",textAlign: TextAlign.left,style: TextStyle(fontSize: 17),),
);
}
return GridView.builder(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: accountData?.hobbies?.length ?? 0,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 5,
crossAxisSpacing: 5,),
itemBuilder: (BuildContext context,
int index) {
return Padding(
padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
child: Text(accountData.hobbies[index]),
);
}
);
},
),
现在收到 NoSuchMethodError 错误:-
Class 'CreateAccountData' has no instance getter 'docs'.
Receiver: Instance of 'CreateAccountData'
Tried calling: docs
答案 0 :(得分:0)
如果您已创建变量并为其赋值,但它仍然显示 getter 'value' was called on null
,
尝试Run
或Restart
您的应用而不是Hot Reload
。因为 Hot Reload
不会调用 initstate()
(变量分配它们的值),它只会被 Restarting
应用调用。
答案 1 :(得分:0)
检查爱好为空
chmod
答案 2 :(得分:0)
在 flutter 2.0 中,我们有空安全。我们需要检查值是否为空或不使用 !在变量后标记。我会在几分钟内发布代码,因为我在学校rn
答案 3 :(得分:0)
将 mi.HTMLBody
包裹在 GridView.builder
中,将 FutureBuilder
作为 getUser()
传递。
future