Beginning FlutterFire

Aug 30 2022 · Dart 2.16, Flutter 3.0, Visual Studio Code 1.69

Part 3: Read & Write Data with the Cloud Firestore

11. Insert & Retrieve Data from Firestore

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 10. Create the Model Class Next episode: 12. Create the Activities Screen

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Now that you’ve created the Activity model class, the Firestore database and added all the dependencies in your project, you can finally write the methods that allow retrieving and writing data to the database.

Future<DocumentReference> insertActivity(Activity activity) async { 
    final newActivity = await activities.add(activity.toMap()); 
    return newActivity; 
  } 
  Future<DocumentReference?> insertActivity(Activity activity) async { 
    try { 
      final newActivity = await activities.add(activity.toMap()); 
      return newActivity; 
    } on Exception catch (e) { 
      print(e.toString()); 
      return null; 
    } 
  } 
  Future<List<Activity>> readActivities() async { 
    final QuerySnapshot<dynamic> snapshot = await activities.get(); 
    final List<Activity> list = []; 
    for (var i = 0; i < snapshot.docs.length; i++) { 
      final activity = Activity.fromMap( 
          snapshot.docs[i].data() as Map<String, dynamic>, snapshot.docs[i].id); 
      activity.id = snapshot.docs[i].id; 
      list.add(activity); 
    } 
    return list; 
  } 
Future testData() async { 

    await insertActivity( 
        Activity(null, 'Running', '12/12/2022', '8.30', '9.30', null)); 
    final activities = await readActivities(); 
    print(activities[0].description); 
  } 
    final helper = FirebaseHelper(); 
    helper.testData();