skip to Main Content

I am trying to retrieve data from Firebase Realtime Database into a list in Flutter using a model.I don’t get snapshot.data how to get data.value. I have read several other posts about using Firebase with Flutter but have not found a clear answer.

Model class screen:

import 'package:firebase_database/firebase_database.dart';
 class DataModel {
    final String id;
    final String name;
    final String price;
    final String qty;

DataModel(
       {required this.id,
       required this.name,
       required this.price,
       required this.qty});

DataModel.fromSnapshot(DataSnapshot snapshot)
  : id = snapshot.key.toString(),
    name = (snapshot.value as Map<String, dynamic>?)?['productName'] ?? '',
    price =
        (snapshot.value as Map<String, dynamic>?)?['productPrice'] ?? '',
    qty = (snapshot.value as Map<String, dynamic>?)?['qty'] ?? '';

toJson() {
  return {
   "productName": name,
   "productPrice": price,
   "qty": qty,
   };
  }
}

Database service with Firebase query:

import 'package:firebase_database/firebase_database.dart';
import 'package:money_management/data_json_model.dart';

 class DatabaseService {
   static List<DataModel> getData() {
    Query needsSnapshot =
    FirebaseDatabase.instance.ref("Money Management").orderByKey();

     //  print(needsSnapshot); // to debug and see if data is returned

      List<DataModel> needs = [];

       Map<dynamic, dynamic> values = needsSnapshot.onValue as Map;
       values.forEach((key, values) {
       needs.add(DataModel.fromSnapshot(values));
       });

       return needs;
      }
   }
  

ListView Page:

import 'package:flutter/material.dart';
import 'package:money_management/data_json_model.dart';

import 'database_service.dart';

   class ListScreen extends StatefulWidget {
   const ListScreen({Key? key}) : super(key: key);

   @override
   State<ListScreen> createState() => _ListScreenState();
   }

  class _ListScreenState extends State<ListScreen> {
  List<DataModel> _needs = [];

  @override
  void initState() {
  super.initState();
  _setupNeeds();
   }

  _setupNeeds() async {
  List<DataModel> needs = DatabaseService.getData();
  setState(() {
  _needs = needs;
   });
  }

  @override
  Widget build(BuildContext context) {
  return RefreshIndicator(
  onRefresh: () => _setupNeeds(),
  child: ListView.builder(
      itemCount: _needs.length,
      itemBuilder: (BuildContext context, int index) {
        DataModel need = _needs[index];
        return Column(
          children: [
            Text(need.id),
            Text(need.name),
            Text(need.price),
            Text(need.qty),
             ],
          );
        }),
     );
  }
}

2

Answers


  1. Try make the method getData() asynchronous and call get() of FirebaseDatabase instead:

    class DatabaseService {
      static Future<List<dynamic>> getData() async {
    
        final snapshot = await FirebaseDatabase.instance
            .ref("Money Management")
            .orderByKey()
            .get();
    
        //  print(snapshot); // to debug and see if data is returned
    
        List<DataModel> needs = [];
    
        Map<dynamic, dynamic> values = snapshot.value as Map;
        values.forEach((key, values) {
          needs.add(DataModel.fromSnapshot(values));
        });
    
        return needs;
      }
    }
    
    Login or Signup to reply.
  2. you can receive data as Map<String,dynamic> in your DataModel like this:

      class DataModel {
    
    late String id;
    late String name;
    late String price;
    late String qty;
    
    DataModel({
       required this.id,
       required this.name,
       required this.price,
       required this.qty
    });
    
    DataModel.fromSnapshot(DataSnapshot snapshot){
    Map<String, dynamic> myData= Map<String,dynamic>.from(snapshot.value as 
    Map);
    id = snapshot.key.toString();
    name = myData["productName"].toString() ?? '';
    price =myData["productPrice"].toString() ?? '';
    qty = myData["qty"].toString() ?? '';
    }
    
    Map<String,dynamic> toJson() {
    return {
    "productName": name,
    "productPrice": price,
    "qty": qty,
    };
    }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search