Search code examples
flutterdartfirebase-realtime-databasezip

cannot fetch data from Firebase database


I have done this, but it says to me class bool has no instance methood [] reciver null tried calling []ok

class Test7 extends StatefulWidget {
  @override
  _Test7State createState() => _Test7State();
}

class _Test7State extends State<Test7> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.deepPurple,
      appBar: AppBar(),
      body:  SingleChildScrollView(
        child: Flexible(
          child: FirebaseAnimatedList(
            shrinkWrap: true,
            query: FirebaseDatabase.instance.reference().child(currentUser.uid), // when i remove child(currentUser.uid)it is work !
            itemBuilder: (BuildContext context, DataSnapshot snapshot,Animation<double> animation,  int index) {
              return ListTile(
                leading: IconButton(
                  onPressed: () {  },
                  icon: Icon(Icons.ac_unit),
                ),
                title: Text(snapshot.value["ok"]),
              );
            },),
        ),
      ),
    );
  }
}

and I have this in Firebase database real time

    NUuhYzfVS9YPYDIox3X6ozhzFiT2
activity: true
ok: "ok"

Solution

  • A FirebaseAnimatedList shows the list of child nodes under the path in the database that you specify in query. If you specify the UID in that path, you end up with these two child nodes:

    activity: true
    ok: "ok"
    

    So your itemBuilder gets called twice: once for activity: true and once for ok: "ok". When you then call snapshot.value["ok"] on that snapshot, there is no such child property anymore.

    Bottom line: a FirebaseAnimatedList only makes sense if you're showing a list of users. When you're showing a specific user, you can't show it in a FirebaseAnimatedList, and you'll typically want to show it in a Text widget, using (for example) a FutureBuilder:

    FutureBuilder(
      future: FirebaseDatabase.instance.reference().child(currentUser.uid).get(),
      builder:
          (BuildContext context, AsyncSnapshot snapshot) {
    
        if (snapshot.hasError) {
          return Text("Something went wrong");
        }
    
        if (snapshot.hasData && !snapshot.data!.exists) {
          return Text("Document does not exist");
        }
    
        if (snapshot.connectionState == ConnectionState.done) {
          return Text(snapshot.data.value["ok"]);
        }
    
        return Text("loading");
      },