android 从Firebase DB获取数据并在Widget中显示

4urapxun  于 2024-01-04  发布在  Android
关注(0)|答案(1)|浏览(145)

我最近开始使用Flutter和Firebase。到目前为止,我已经创建了一个表单页面来读取用户输入并将其上传到Firebase Realtime DB。但是,我不知道从DB中获取数据并在Widget中显示的最佳方法。
到目前为止,我可以做一些如下的工作:
x1c 0d1x的数据
为了实现这一点,我使用下面的函数将数据提取到一个列表中,然后打印该列表。

  1. void readData() {
  2. ref.child("").onValue.listen((event) {
  3. DataSnapshot snapshot = event.snapshot;
  4. if (snapshot.value != null) {
  5. dataList.clear();
  6. if (snapshot.value is Map) {
  7. (snapshot.value as Map).forEach((key, value) {
  8. dataList.add("$key: $value");
  9. });
  10. setState(() {
  11. });
  12. }
  13. } else {
  14. print("No data available.");
  15. }
  16. });

字符串
这给了我正确的数据,但它根本没有组织,并在一个适当的小部件。我想做的是创建一个单独的小部件为每个条目从数据库和没有的ID-“Nmc 6 zn**"。
另外,我使用ListView Builder实现上述功能。

  1. child: ListView.builder(
  2. itemCount: dataList.length,
  3. itemBuilder: (context, index) {
  4. return Column(
  5. children: [
  6. ListTile(
  7. title: Text(
  8. dataList[index],
  9. style: TextStyle(
  10. fontWeight: FontWeight.bold,
  11. fontSize: 16.0,
  12. ),
  13. ),
  14. ),
  15. Divider(
  16. thickness: 1.0,
  17. color: Colors.grey[300],
  18. ),
  19. ],
  20. );
  21. },
  22. ),

qcbq4gxm

qcbq4gxm1#

我将分三步回答你的问题:

1:

..然而,我不知道从DB中获取数据并在Widget中显示的最佳方法。
实现此目的的一种方法是创建数据的自定义模型表示,就像它在Firestore中显示的那样。例如:

  1. class MyModel {
  2. final String owner;
  3. final String email;
  4. MyModel({required this.owner, required this.email});
  5. factory MyModel.fromJson(Map<dynamic, dynamic> json) {
  6. return MyModel(
  7. owner: json['owner'] as String,
  8. email: json['email'] as String,
  9. // --> add other fields here
  10. );
  11. }
  12. }

字符串

2:

.我想做的是从数据库中为每个条目创建一个单独的小部件,并且没有ID-“Nmc 6 zn**"。
只需创建一个sperate小部件,并传入上面创建的模型:

  1. class CustomTextWidget extends StatelessWidget {
  2. final MyModel model;
  3. const CustomTextWidget(this.model, {Key? key}) : super(key: key);
  4. @override
  5. Widget build(BuildContext context) {
  6. return Text(
  7. model.owner, // <-- use the model here
  8. style: TextStyle(
  9. fontSize: 20,
  10. fontWeight: FontWeight.bold,
  11. ),
  12. );
  13. }
  14. }

3:

示例用法:

  1. ListView.builder(
  2. itemCount: documents.length,
  3. itemBuilder: (context, index) {
  4. var data = documents[index].data() as Map<dynamic, dynamic>;
  5. var model = MyModel.fromJson(data);
  6. return CustomTextWidget(model); // ---> Using the widget here
  7. },
  8. )


下面是一个完整的可运行示例,(我使用的是StreamBuilder而不是你的readData方法)在IDE中查看它以获得更好的理解:

  1. import 'package:flutter/material.dart';
  2. import 'package:cloud_firestore/cloud_firestore.dart';
  3. import 'package:firebase_core/firebase_core.dart';
  4. import 'firebase_options.dart';
  5. void main() async {
  6. WidgetsFlutterBinding.ensureInitialized();
  7. // YOUR FIREBASE INITIALIZATION CODE HERE
  8. // for example:
  9. await Firebase.initializeApp(
  10. options: DefaultFirebaseOptions.currentPlatform,
  11. );
  12. runApp(MyApp());
  13. }
  14. class MyApp extends StatelessWidget {
  15. @override
  16. Widget build(BuildContext context) {
  17. return MaterialApp(
  18. title: 'Material App',
  19. home: Scaffold(
  20. appBar: AppBar(
  21. title: Text('Material App Bar'),
  22. ),
  23. body: StreamBuilder<QuerySnapshot>(
  24. stream: FirebaseFirestore.instance
  25. .collection('users')
  26. .snapshots(), // <-- Replace with your stream
  27. builder: (context, snapshot) {
  28. if (snapshot.hasError) {
  29. return Text('Something went wrong');
  30. }
  31. if (snapshot.connectionState == ConnectionState.waiting) {
  32. return CircularProgressIndicator();
  33. }
  34. var documents = snapshot.data?.docs ?? [];
  35. return ListView.builder(
  36. itemCount: documents.length,
  37. itemBuilder: (context, index) {
  38. var data = documents[index].data() as Map<dynamic, dynamic>;
  39. var model = MyModel.fromJson(data);
  40. return CustomTextWidget(model); // Use your custom widget here
  41. },
  42. );
  43. },
  44. ),
  45. ),
  46. );
  47. }
  48. }
  49. class MyModel {
  50. final String owner;
  51. final String email;
  52. MyModel({required this.owner, required this.email});
  53. factory MyModel.fromJson(Map<dynamic, dynamic> json) {
  54. return MyModel(
  55. owner: json['owner'] as String,
  56. email: json['email'] as String,
  57. // --> add other fields here
  58. );
  59. }
  60. }
  61. class CustomTextWidget extends StatelessWidget {
  62. final MyModel model;
  63. const CustomTextWidget(this.model, {Key? key}) : super(key: key);
  64. @override
  65. Widget build(BuildContext context) {
  66. return Text(
  67. model.owner, // <-- use the model here
  68. style: TextStyle(
  69. fontSize: 20,
  70. fontWeight: FontWeight.bold,
  71. ),
  72. );
  73. }
  74. }

展开查看全部

相关问题