Thinking & coding: Building the Firestore service library.

The next step is to write the Firestore Service.

In this library I put the function that will retrieve my data collection from the backend. After that, state management will be used, as a separation layer, to link the data to the UI.

So there are 3 parts, the UI with its data model, the backend with its service library with the necessary methods to request data collection 'events' and the link between them with the state management.


I searched the Firestore documentation to find the correct way, that fits my app, to access the backend.


What I need is that when starting the app, the data collection from the backend is read 1 time. And fortunately there is a suitable way for this, which is described on the following web page https://firebase.flutter.dev/docs/firestore/usage/

An other great reference to get some info is a artikel of Atul Sharma. https://atul-sharma-94062.medium.com/how-to-use-cloud-firestore-with-flutter-e6f9e8821b27

In my app only data will be read from the backend, en there will be no data to the backend. So i dont need the complete CRUD actions. Only the read methode.


Code en the problems I encountered.

the only TIP I can give in writing this code, is to write the complete function on 1 line and reformat afterwards. I had to restart 2 times because i missed a bracked or had a bracket on the wrong spot. ;-)

I understand the code also better when the mappings are written on one line.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:my_first_production/models/event_model.dart';


class FirestoreService {
  // creating a instance of the collection Events
  //CollectionReference _events = FirebaseFirestore.instance.collection('events');

  final databaseReference = FirebaseFirestore.instance;
    
   // get events 

   void getEvents() {
     databaseReference
       .collection('Events')
       .snapshots()
       .map((snapshots) => snapshots.docs
       .map((docs) => Events.fromJson(docs.data()))
       .toList())
       ;
   }

  // create events -- no need in this app

  // update events -- no need in this app

  // delete events -- no need in this app 

}


So next sesion will be about two things. The first will be the state management, im scared already, and displaying the data from the backend on the correct page.

If you want to help or see a misstake in the code, please write a comment. Thanks in advance.

C U all next time,


Do, believe and be happy,


Stefaan



Comments

Popular posts from this blog

Thinking & coding: Linking Firebase to my Flutter App. Watch out for a important detail.

Software developer yes, but where to begin?

Thinking & coding: Small but important code implementations.