Home > other >  Flutter: How to fetch (all) of a child data from firebase realtime database in streambuilder/futureb
Flutter: How to fetch (all) of a child data from firebase realtime database in streambuilder/futureb

Time:01-20

I'm trying to fetch all of the child('users') data from realtime database in a StreamBuilder or FutureBuilder through out a ListView.builder(), but unfortunately it always returns null!

So how can i do it?

Here is what i have tried to do:

import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';


class HomeWidget extends StatelessWidget {
  const HomeWidget({ Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
     final dbRef = FirebaseDatabase.instance.ref().child("users");

    return FutureBuilder(
      future: dbRef.once(),
      builder: (ctx, AsyncSnapshot snapshot){
        if(snapshot.connectionState == ConnectionState.waiting){
                return const Center(child: CircularProgressIndicator());
              }
        if(snapshot.hasData){
final userS = snapshot.data!.snapshot.value;
          return ListView.builder(
            itemCount: userS.length,
            itemBuilder: (BuildContext ctx, i)=> Container(
              height: 100,
              width: 100,
              child:  Card(
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                child: Column(
                  children: [
                    Text(userS[i]['username']),
                    Text(userS[i]['password'])
                  ],
                ),
              ),
            ),
            );
        }
        return const Center(child: Text('There is something wrong!'),);
      },
      );
  }
}

enter image description here

enter image description here

CodePudding user response:

This code in your app:

final userS = snapshot.data!.snapshot.value

You're taking the value of the DataSnapshot object, which in your case is going to be a Map<String, dynamic>. And a Map doesn't have an [] accessor, which is why you get an error.

If you want to get the results by index, it's probably easier to keep the DataSnapshot:

final userS = snapshot.data!.snapshot;

And then access its children by their index:

children: [
  Text(userS.children.toList()[i].child('username').value),
  Text(userS.children.toList()[i].child('password').value)
],

So here we use userS.children.toList() to get the child snapshots into a list, and then look up the correct snapshot by its index. From there we can then get the value of its username and password child properties.

  •  Tags:  
  • Related