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

Take your career further with a raywenderlich.com Pro subscription. 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.

Insert & Retrieve Data from Firestore Pro

This video was last updated on Aug 30 2022

Now that you’ve created the Activity model class, you can finally write the methods that allow retrieving and writing data to the database.

Contributors

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

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(); 

Reviews

Comments