Home > Net >  Flutter Firestore read
Flutter Firestore read

Time:12-28

I would like to change this code that reads from Real time database to firestore. Below is the code that is reading from realtime database :

 final dbRef = FirebaseDatabase.instance.reference().child("users");
  List<Map<dynamic, dynamic>> lists = [];
  var usersList;
  final formatter = intl.NumberFormat("#,##0.0######"); // for price change
  final percentageFormat = intl.NumberFormat("##0.0#"); // for price change
  final GlobalKey<ExpansionTileCardState> cardA = new GlobalKey();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color.fromRGBO(34, 44, 59, 1.0),

        body: Center(
          child: Column(

            children: [ SizedBox(
              height: 50.0,
            ),
              Image.asset(
                logoImage,
                fit: BoxFit.contain,
                color: Color.fromRGBO(251, 199, 0, 1.0),
                height: 100.0,
                width: 100.0,
              ),Text(
                '[users]',
                style: TextStyle(
                  fontSize: 20,
                  color: Color.fromRGBO(251, 199, 0, 1.0),
                ),
              ),
              FutureBuilder(
                  future: dbRef.orderByChild("type").equalTo("Free").once(),
                  builder: (context, AsyncSnapshot<DataSnapshot> snapshot) {
                    if (snapshot.hasData) {
                      lists.clear();
                      Map<dynamic, dynamic> values = snapshot.data.value;
                      values.forEach((key, values) {
                        lists.add(values);
                      });
                      return new ListView.builder(
                          shrinkWrap: true,
                          itemCount: lists.length,
                          itemBuilder: (BuildContext context, int index) {
                            Divider(
                              thickness: 1.0,
                              height: 1.0,
                            );
                            return ExpansionTileCard(
                              baseColor:  Color.fromRGBO(34, 44, 59, 1.0),
                              expandedColor: Color.fromRGBO(24, 31, 42, 1.0),

                              leading: CircleAvatar(
                                child: Image.asset("assets/images/giphyy.gif",), backgroundColor: Colors.transparent,),
                              title: Text(
                                lists[index]["username"].toString(),
                                style: TextStyle(
                                    color: Color.fromRGBO(251, 199, 0, 1.0)),
                              ),

                              children: <Widget>[
                                Align(
                                  alignment: Alignment.centerLeft,
                                  child: Padding(
                                    padding: const EdgeInsets.symmetric(
                                      horizontal: 16.0,
                                      vertical: 8.0,
                                    ),
                                    child: Text(lists[index]["userinfo"].toString(),
                                      style: TextStyle(fontWeight: FontWeight.bold,
                                          color: Color.fromRGBO(251, 199, 0, 1.0)),
                                    ),
                                  ),
                                ),
                                ],
                            );
                          });
                    }
                    return CircularProgressIndicator();
                  }),
            ],
          ),
        ));
  }

I did the update and adding new post section, but i see after many searches on googling nothing is fixing my issue plus i edited the code from Firebase Firestore official documentation and nothing works.. so that the view or read data is hard for me.

Thanks in advance for your kind cooperation!

CodePudding user response:

final Future<QuerySnapshot<Map<String, dynamic>>> query = FirebaseFirestore
    .instance
    .collection('users')
    .orderBy('type')
    .where('type', isEqualTo: 'Free')
    .get();
// NB: This wont return docs where type doesn't exist.
var usersList;
final formatter = intl.NumberFormat("#,##0.0######"); // for price change
final percentageFormat = intl.NumberFormat("##0.0#"); // for price change
final GlobalKey<ExpansionTileCardState> cardA = new GlobalKey();

@override
Widget build(BuildContext context) {
  return Scaffold(
    backgroundColor: Color.fromRGBO(34, 44, 59, 1.0),
    body: Center(
      child: Column(
        children: [
          SizedBox(
            height: 50.0,
          ),
          Image.asset(
            logoImage,
            fit: BoxFit.contain,
            color: Color.fromRGBO(251, 199, 0, 1.0),
            height: 100.0,
            width: 100.0,
          ),
          Text(
            '[users]',
            style: TextStyle(
              fontSize: 20,
              color: Color.fromRGBO(251, 199, 0, 1.0),
            ),
          ),
          FutureBuilder(
            future: query,
            builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
              if (snapshot.hasError) return Text('Something went wrong');
              if (snapshot.connectionState == ConnectionState.waiting)
                return CircularProgressIndicator();

              List<Map<dynamic, dynamic>> lists =
                  snapshot.data.docs.map((e) => e.data()).toList();
              return new ListView.builder(
                shrinkWrap: true,
                itemCount: lists.length,
                itemBuilder: (BuildContext context, int index) {
                  Divider(
                    thickness: 1.0,
                    height: 1.0,
                  );
                  return ExpansionTileCard(
                    baseColor: Color.fromRGBO(34, 44, 59, 1.0),
                    expandedColor: Color.fromRGBO(24, 31, 42, 1.0),
                    leading: CircleAvatar(
                      child: Image.asset(
                        "assets/images/giphyy.gif",
                      ),
                      backgroundColor: Colors.transparent,
                    ),
                    title: Text(
                      lists[index]["username"].toString(),
                      style: TextStyle(
                        color: Color.fromRGBO(251, 199, 0, 1.0),
                      ),
                    ),
                    children: <Widget>[
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Padding(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 16.0,
                            vertical: 8.0,
                          ),
                          child: Text(
                            lists[index]["userinfo"].toString(),
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Color.fromRGBO(251, 199, 0, 1.0),
                            ),
                          ),
                        ),
                      ),
                    ],
                  );
                },
              );
            },
          ),
        ],
      ),
    ),
  );
}

CodePudding user response:

Change and try this code :

StreamBuilder(
  stream: dbRef.orderByChild("type").equalTo("Free").onValue,
  builder: (context,  snapshot) {
   if (!snapshot.hasData || snapshot.hasError) {
     return Text('ERROR!');
   }
   if (snapshot.connectionState == ConnectionState.waiting) {
     return Text('Loading..');
   }
   if (snapshot.hasData) {
      lists.clear();
      Map<dynamic, dynamic> values = snapshot.data.value;
      values.forEach((key, values) {
      lists.add(values);
     });
   }
  return new ListView.builder... // than write you code

  • Related