提问者:小点点

如何从Firebase实时数据库中读取数据?


我正在尝试读取我的Flutter应用程序中的firebase实时数据库中的数据,并将其分配给模型类,但是,我在控制台中得到了以下错误。

E/flutter ( 9052): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: NoSuchMethodError: Class 'List<dynamic>' has no instance getter 'keys'.
E/flutter ( 9052): Receiver: _List len:3
E/flutter ( 9052): Tried calling: keys
E/flutter ( 9052): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter ( 9052): #1      _MyHomePageState.initState.<anonymous closure> (package:app/main.dart:64:27)
E/flutter ( 9052): #2      _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter ( 9052): #3      _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter ( 9052): #4      _FutureListener.handleValue (dart:async/future_impl.dart:152:18)
E/flutter ( 9052): #5      Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:704:45)
E/flutter ( 9052): #6      Future._propagateToListeners (dart:async/future_impl.dart:733:32)
E/flutter ( 9052): #7      Future._completeWithValue (dart:async/future_impl.dart:539:5)
E/flutter ( 9052): #8      _completeOnAsyncReturn (dart:async-patch/async_patch.dart:254:13)
E/flutter ( 9052): #9      Query.once (package:firebase_database/src/query.dart)
E/flutter ( 9052): <asynchronous suspension>

下面是我到目前为止所做的代码

员工类别

class Employee {

  final String id;
  final String name;
  final String email;
  final String emp_id;

  const Employee({this.id,this.name,this.email,this.emp_id});
}
import 'dart:convert';

import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:shimmer/shimmer.dart';
import 'Employee.dart';



class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,

      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
 List <Employee> myAllData = [];
   
  @override
  void initState() {
  super.initState();
    DatabaseReference ref = FirebaseDatabase.instance.reference();
    ref.child('employee').once().then((DataSnapshot snap){
    var keys = snap.value.keys;
      var data = snap.value;
        for (var key in keys){
          Employee d = new Employee(
            id : data [key]['id'],
            name : data[key]['name'],
            email : data[key]['email'],
            emp_id: data[key]['emp_id']
          );
          myAllData.add(d);
        }


      setState(() {
       print('Length : ${myAllData.length}');
      });
    });

   }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      );
  }

}

我不知道我做错了什么,请帮我解决这个问题


共1个答案

匿名用户

错误似乎很明显。您正在调用var keys=snap.value.keys;,而snap.value上没有keys。由此看来,您认为snap.value是一个map对象,事实似乎并非如此。

从您的数据结构来看,snap.value更可能是一个list对象。

这是因为Firebase用顺序的数字键解释对象,数字键是数组。如果确实是这种情况(您可以通过在调试器中运行代码轻松地验证这一点),则可以使用以下命令对列表进行迭代:

for (var child in snap.value){

另请参阅:

  • 最佳实践:FireBase中的数组。