Home > Back-end >  Getting a JSON file using flutterfire stack
Getting a JSON file using flutterfire stack

Time:10-14

I am using firebase's realtime database store JSON files with google map marker locations. I have been using the google maps API. However, I cannot figure out how to get the json from realtime database to the flutter code, specifically in this section:

Future<Locations> getGoogleOffices() async {
  return Locations.fromJson(
    json.decode(
      // get json file
  );
}

Previously I was referencing the JSON file locally to bug fix the app. I would greatly appreciate any help and apologies as I am quite new to flutter!

CodePudding user response:

Once you have well setup the Fireabse application instance:

final FirebaseApp firebaseApp = await Firebase.initializeApp(); // somewhere in your `main` starter method

Firestore Database

You can query a Firestore collection data as follows:

Future<Locations> getGoogleOffices() async {
  DocumentSnapshot documentSnapshot = await FirebaseFirestore.instance.collection('locations').doc('documentId').get();
  return Locations.fromJson(
    json.decode(
      documentSnapshot.data()
  );
}

EDIT: Firebase Realtime Database

In order to access data from Fireabse Realtime Database instead of Firestore, you can attempt something as follows:

Future<Locations> getGoogleOffices() async {
  final DatabaseReference db = FirebaseDatabase(app: firebaseApp).reference();
  final DataSnapshot data = await db.child('locations').get();
  return Locations.fromJson(
    json.decode(
      data!.value
  );
}

The DatabaseReference#get API call will feed a reference to the most up-to-date result for this query.

  • Related