Emi*_*rde 5 dart firebase-realtime-database flutter
我必须从 Firebase 数据库获取数据,并通过键“key”获取所有数据并将它们插入“postsList”中。为此,我使用了 for-in 循环。后者给我一个错误。
错误是:“可为 null 的表达式不能用作 for-in 循环中的迭代器。在将其用作迭代器之前,请尝试检查该值是否不是“null”。”
class _HomePageState extends State<HomePage> {
List<Posts> postsList = [];
@override
void initState() {
super.initState();
DatabaseReference postsRef = FirebaseDatabase.instance.reference().child("Posts");
postsRef.once().then((snap)
{
var keys = snap.snapshot.key;
var values = snap.snapshot.value;
postsList.clear();
for (var individual in keys) {
Posts posts = Posts(
values[individual]['url'],
values[individual]['descrizione'],
values[individual]['data'],
values[individual]['ora'],
);
postsList.add(posts);
}
setState(()
{
print('Length : $postsList.length');
});
});
}
Run Code Online (Sandbox Code Playgroud)
小智 8
添加!后面的键,例如:for(key in keys!
@override
void initState() {
super.initState();
DatabaseReference postsRef = FirebaseDatabase.instance.reference().child("Posts");
postsRef.once().then((snap)
{
var keys = snap.snapshot.key;
var values = snap.snapshot.value;
postsList.clear();
for (var individual in keys!) {
Posts posts = Posts(
values[individual]['url'],
values[individual]['descrizione'],
values[individual]['data'],
values[individual]['ora'],
);
postsList.add(posts);
}
setState(()
{
print('Length : $postsList.length');
});
});
}
Run Code Online (Sandbox Code Playgroud)
错误消息应附带指向此文档页面的链接,该链接涉及未经检查的可空值的使用。正如错误所示,keys您使用的变量for (var individual in keys) {可以为 null,这是不允许的。您应该检查它是否为空,或者断言它不为空:
if (keys != null) {
for (var individual in keys) {
Posts posts = Posts(
values[individual]['url'],
values[individual]['descrizione'],
values[individual]['data'],
values[individual]['ora'],
);
postsList.add(posts);
}
}
Run Code Online (Sandbox Code Playgroud)
上面修复了语法/编译器问题,但是您的代码中很可能存在其他问题,因为我怀疑您的keys变量将是具有值的单个字符串Posts。如果是这种情况,请考虑使用values与上面相同的空检查进行循环。
Map<String,int>.from(event.snapshot.value)
map.forEach((k, v) => print("键:$k,值:$v"));
DatabaseReference postsRef = FirebaseDatabase.instance.reference().child("Posts");
postsRef.once().then((snap) {
// Get a map of the top-level post keys and post values
var map = Map<String, dynamic>.from(snap.snapshot.value);
postsList.clear();
// Loop over the post keys and post values
map.forEach((key, value) {
// Get the values for this post as another map
var values = Map<String, dynamic>.from(map);
Posts posts = Posts(
values['url'],
values['descrizione'],
values['data'],
values['ora'],
);
postsList.add(posts);
});
setState(() {
print('Length : $postsList.length');
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6560 次 |
| 最近记录: |