【发布时间】:2019-07-01 00:46:00
【问题描述】:
我想根据来自 Firebase Auth 的用户 ID 显示所有(嵌套的)Firebase 实时数据库数据。我使用颤振安卓。
我的数据库是这样的:
而我的代码大概是这样的:
home.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(),
);
}
}
和我的模型类:
todo.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,
};
}
}
我已经做到了。
但是,如果我将数据库更改为这样的内容(添加嵌套子项)怎么办:
如何从用户 id Firebase auth 获取所有子数据?
提前致谢
【问题讨论】:
-
还没有答案,有人知道吗?
-
你找到解决方案了吗?
-
@Farhana 不,我只是更改了我的数据库结构,使其更简单。
标签: firebase flutter dart firebase-realtime-database