gpt4 book ai didi

firebase - 如何使用Flutter从Firebase数据库查询中打印列表?

转载 作者:行者123 更新时间:2023-12-03 04:14:14 24 4
gpt4 key购买 nike

我正在尝试从我的Firebase数据库中打印属性列表。当前数据库的结构如下:

enter image description here

我首先要在控制台上打印显示名称的列表,以便可以看到它的工作原理,然后再将其添加到ListView中。任何帮助表示赞赏!

import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

// This is the model class
class Mod {
final String name;
final String nextEpisode;
final String prevEpisode;

Mod(this.name, this.nextEpisode, this.prevEpisode);

Mod.fromJson(Map<String, dynamic> json)
: name = json['name'],
nextEpisode = json['nextEpisode'],
prevEpisode = json['prevEpisode'];
}


// This is the screen class
class FTest2 extends StatefulWidget {
@override
_FTest2State createState() => _FTest2State();
}

class _FTest2State extends State<FTest2> {

List<Mod> list = List();

MakeCall() {
final mainReference = FirebaseDatabase.instance.reference();
mainReference.child('-M5Uol7Xldnc8wvNXnNg').once().then((DataSnapshot dataSnapshot){
this.setState(() {
for(var value in dataSnapshot.value){
list.add(Mod.fromJson(value));
}
});
});
print(list);
}

void getData() {
MakeCall();
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('This is App Bar for the FB Test')),
body: Column(
children: <Widget>[
RaisedButton(
child: Text('Press for data'),
onPressed: () {
getData();
},
),
],
));
}
}

最佳答案

您正在遍历一个特定节目的节点,这意味着value实际上是该节目下的子属性之一:namenextEpisodeprevEpisode。您可能正在寻找的是听所有节目的onChildAdded,然后为每个节目获取name属性:

mainReference.child('shows')
.onChildAdded
.forEach((event) => {
print(event.snapshot.key+": "+event.snapshot.value.toString());
this.setState(() {
list.add(Mod.fromJson(event.snapshot.value["name"]));
});
});

另请参见几周前的答复表: Flutter: Firebase Real-Time database orderByChild has no impact on query result

关于firebase - 如何使用Flutter从Firebase数据库查询中打印列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61601524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com