gpt4 book ai didi

firebase - 如何在 Flutter 中获取嵌套 firebase 数据的所有子数据?

转载 作者:行者123 更新时间:2023-12-04 13:02:01 26 4
gpt4 key购买 nike

我想根据 Firebase Auth 中的用户 ID 显示所有(嵌套的)Firebase 实时数据库数据。我使用 Flutter Android。

我的数据库是这样的:

enter image description here

我的代码是这样的:

家.dart

class _HomePageState extends State<HomePage> {
List<Todo> _dataList;

final FirebaseDatabase _database = FirebaseDatabase.instance;

StreamSubscription<Event> _onTodoAddedSubscription;
Query _todoQuery;

@override
void initState() {
super.initState();
_dataList = List();
_todoQuery = _database.reference().child(widget.userId);
_onTodoAddedSubscription = _todoQuery.onChildAdded.listen(_onEntryAdded);
}

@override
void dispose() {
_onTodoAddedSubscription.cancel();
super.dispose();
}

_onEntryAdded(Event event) {
setState(() {
_dataList.add(Todo.fromSnapshot(event.snapshot));
});
}

Widget _showTodoList() {
if (_dataList.length > 0) {
return ListView.builder(
shrinkWrap: true,
itemCount: _dataList.length,
itemBuilder: (BuildContext context, int index) {
String todoId = _dataList[index].key;
bool status = _dataList[index].status;
int datetime = _dataList[index].datetime;
double current = _dataList[index].current;
double voltage = _dataList[index].voltage;
});
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: _showTodoList(),
);
}
}

和我的模型类:

待办事项.dart
class Todo {
int datetime;
double current;
double voltage;
String key;
bool status;
String userId;

Todo(this.datetime, this.userId, this.status, this.current, this.voltage);

Todo.fromSnapshot(DataSnapshot snapshot)
: key = snapshot.key,
status = snapshot.value["status"],
datetime = snapshot.value["datetime"],
current = snapshot.value["current"],
voltage = snapshot.value["voltage"];

toJson() {
return {
"status": status,
"datetime": datetime,
"current": current,
"voltage": voltage,
};
}
}

我已经这样做了。

但是,如果我将数据库更改为这样的内容(添加嵌套子项)怎么办:
enter image description here

如何根据用户 ID Firebase 身份验证获取所有子数据?

提前致谢

最佳答案

在构建数据库时,您需要考虑到它必须是平面结构。如果将结构更改为第二个图像,则可以执行以下操作:

final FirebaseDatabase _database = FirebaseDatabase.instance;
User currentUser = FirebaseAuth.instance.currentUser;

var ref = _database.reference().child(currentUser.uid);
ref.once().then((DataSnapshot snapshot){
print(snapshot.value);
print(snapshot.key);
snapshot.value.forEach((key,values) {
print(values);
});
});
这里首先获取数据库的一个实例,获取当前登录的用户,然后使用 once()您可以获取数据,以便能够访问嵌套的字段,然后您必须使用 forEach()datasnapshot 内迭代.

关于firebase - 如何在 Flutter 中获取嵌套 firebase 数据的所有子数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54564226/

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