Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Flutter ♥ Firebase. How to quickly prepare a co...

Flutter ♥ Firebase. How to quickly prepare a complete mobile solution?

In July 2018, I've prepared an app for my friends and me to share opinions on the movies we were watching at one of the film festivals in Poland. That was the first time I've used Flutter, and I've chosen Firebase for authentication and storing the data.

In this presentation I share some thoughts on utilizing Firebase services in Flutter apps, with the context of my journey from an idea to a working app and finding myself in a new programming environment.

This deck was used during Flutter Live 2018 Viewing Party organized by GDG Kraków and Miquido.

Miłosz Lewandowski

December 04, 2018
Tweet

More Decks by Miłosz Lewandowski

Other Decks in Programming

Transcript

  1. Flutter ♥ Firebase How to quickly prepare a complete mobile

    solution? Miłosz Lewandowski Android dev @ Miquido @plnice
  2. #MyFlutterStory • Arthouse movies geek • Attending New Horizons IFF

    in July • No festival app :-( • Wanted to prepare an app for me and my friends to communicate during the festival
  3. App requirements Your festival schedule Screening: Yes-No-Maybe Recommendations (!) Movie

    descriptions Links to IMDB/Filmweb One-click login Activity feed Cross-platform (!)
  4. Recommendations • 10 days • ~250 movies • ~600 screenings

    • ~2-3 screenings per movie (on average) • You can attend only 50 screenings (5 per day) • Impossible to watch all the movies • Need to carefully select movies, mistakes can be painful
  5. Recommendations 1. Somebody attends one of the first screenings of

    Movie A 2. She sends a highly positive recommendation 3. Other people know that they cannot skip the movie 1. Somebody attends one of the first screenings of Movie B 2. She send a highly negative recommendation 3. Other people know that they should skip the movie
  6. Cross-platform • Survey: Which platform do you use? • Results:

    50% Android, 50% iOS :-/ • Let’s try Flutter!
  7. I need a backend • Don’t keep festival timetable in

    app • Yes-No-Maybe store • Recommendations store • Activity feed • Let’s try Firebase!
  8. I made it! • July 7th - initial commit •

    July 23rd - last commit • July 26th - first day of the festival
  9. Topics to cover 1. Setting up Firebase in a Flutter

    environment 2. Firebase Authentication a. Futures, Async/Await b. FutureBuilder 3. Cloud Firestore a. Snapshots, SnapshotBuilder, b. QuerySnapshot, DocumentSnapshot, c. updating the data 4. What to do next? 5. Summary 6. Resources
  10. Setting up Firebase 1. Create new project in Firebase Console

    2. Prepare both Android and iOS setup within it :-/ 3. Download GoogleService-Info.plist (for iOS) and google-services.json (for Android); please them in appropriate location in Flutter project :-/ 4. Additional google-services dependency setup in Android Gradle files :-/ 5. Add FlutterFire dependencies
  11. Authentication flow 1. Check if signed in 2. If yes,

    display user avatar 3. If no, display login button 4. After user taps login button: a. Sign in using Google Account b. Sign in to Firebase using Google tokens c. Handle result
  12. Futures • Future<*> represents asynchronous operation result • Suspend execution

    via await keyword in async function • Part of Dart language
  13. Futures and Google/Firebase Authentication class Authentication { final FirebaseAuth _auth

    = FirebaseAuth.instance; Future<FirebaseUser> getCurrentUser() async { final FirebaseUser currentUser = await _auth.currentUser(); return currentUser; } }
  14. Futures and Google/Firebase Authentication final FirebaseAuth _auth = FirebaseAuth.instance; final

    GoogleSignIn _googleSignIn = GoogleSignIn(); Future<FirebaseUser> signInWithGoogle() async { final GoogleSignInAccount googleUser = await _googleSignIn.signIn(); final GoogleSignInAuthentication googleAuth = await googleUser.authentication; return await _auth.signInWithGoogle( accessToken: googleAuth.accessToken, // OAuth2 access token idToken: googleAuth.idToken, // OpenID Connect ID ); }
  15. What to do with our Futures? • We need a

    way to suspend our widget building function and transform our Future to Widget • FutureBuilder FTW! • FutureBuilder is a Widget that builds itself based on the latest snapshot of interaction with Future • FutureBuilder operates on an AsyncSnapshot class, which (briefly speaking) wraps data, error, state of asynchronous computation snapshot • Part of Flutter ecosystem
  16. Cloud Firestore • Flexible, scalable NoSQL cloud database • Large

    collections of small documents • Documents can contain subcollections and nested objects • Both can include primitive fields
  17. Use case: activity stream • List of activities of all

    users for the last 3 days • We want real-time updates • We can’t use Futures, this is not an use case of one-time async operation
  18. Streams • Streams provide an asynchronous sequence of data. •

    Suspend execution via await for construct in async function • Part of Dart language
  19. Streams and Cloud Firestore final Firestore firestore = Firestore(app: FirebaseApp.instance);

    Stream<QuerySnapshot> getActivitiesStream() { return firestore .collection("activities") .where("dateTime", isGreaterThan: DateTime.now().subtract(Duration(days: 3))) .orderBy("dateTime", descending: true) .snapshots(); }
  20. QuerySnapshot • A QuerySnapshot contains zero or more DocumentSnapshot objects

    • A DocumentSnapshot contains data read from a document in a Firestore database DocumentSnapshot document = querySnapshot.documents // or List<DocumentChanges> documentChanges = querySnapshot.documentChanges String title = document['title']; // 'title' is a key in Document
  21. What to do with our Stream? • We need a

    way to suspend our widget building function and transform snapshots from our Stream to Widget • StreamBuilder FTW! • StreamBuilder is a Widget that builds itself based on the latest snapshot of interaction with Stream • Part of Flutter ecosystem
  22. StreamBuilder return StreamBuilder<QuerySnapshot>( stream: getActivitiesStream(), builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot)

    { if (!snapshot.hasData) return LoadingWidget(); if (snapshot.error != null) return DataLoadingErrorWidget(); if (snapshot.data.documents.length == 0) return EmptyStateWidget();
  23. StreamBuilder final List<Activity> activities = parse(snapshot.data.documents); return ListView.builder( itemCount: activities.length,

    itemBuilder: (BuildContext context, int index) { return ActivityWidget(activities[index]); } ) } )
  24. Adding objects to Cloud Firestore void addComment(Movie movie, String comment)

    async { FirebaseUser user = await _authentication.getCurrentUser(); firestore.runTransaction((tx) async { DocumentReference commentRef = firestore.collection('comments').document(); await tx.set(commentRef, { 'movieId': movie.id, 'userId': user.id, 'comment': comment }); }); }
  25. What to do next? • Cloud Functions: final dynamic resp

    = await CloudFunctions.instance.call( functionName: 'repeat', parameters: <String, dynamic>{ 'param1': 'param value' }); print(resp);
  26. What to do next? • ML Kit: final File imageFile

    = getImageFile(); final FirebaseVisionImage visionImage = FirebaseVisionImage.fromFile(imageFile); final FaceDetector faceDetector = FirebaseVision.instance().faceDetector(); final List<Face> faces = await faceDetector.detectInImage(visionImage); // Face: boundingBox, landmarks, and even things like smilingProbability // or eyeOpenProbability ;-)
  27. Summary • Use Flutter, it’s cool • Use Firebase, it’s

    even more cool • Understand the asynchronous world • There’s much more to discover in both Firebase and Flutter ecosystems and they play well with each other
  28. Resources • FlutterFire: https://firebaseopensource.com/projects/flutter/plugins/ • Firebase Docs: https://firebase.google.com/docs/flutter/setup • Dart

    Tutorials: https://www.dartlang.org/tutorials • Flutter Docs: https://flutter.io/docs • Flutter SDK Docs: https://docs.flutter.io/index.html