How to integrate your iOS Flutter App with Firebase on MacOS

How to integrate your iOS Flutter App with Firebase on MacOS

In this tutorial I am going to show you how to connect your Flutter iOS application to the Firebase Platform on a Mac Computer so you can utilize the powerful services provided by the firebase API in your future endeavors…

In this tutorial I am going to show you how to connect your Flutter iOS application to the Firebase Platform on a Mac Computer so you can utilize the powerful services provided by the firebase API in your future endeavors…

Firebase is a mobile app development platform developed by Firebase, Inc. in 2011, and then Acquired by Google in 2014. It provides various features such as Cloud Storage, Authentication and an ML kit, which are essential to developing modern mobile applications. Additionally, it provides services such as Performance Monitoring, Crashlytics and Google Analytics to help you improve the quality of your applications.

1. Readying a Gmail Account and a Flutter Project

In order to utilize services from Firebase and Google Cloud Platform, you will need a Google Account. If you do not have one, simply following the page instructions here to register for one.

This tutorial is going to show you how to connect your existing Flutter application to the Firebase platform. If you are interested in how to create your first Flutter application, I have a tutorial on How to create your first iOS Flutter app on MacOS. By the end of that tutorial, you should have a hello_world application ready in the simulator and understand how to alter the application by modifying the main.dart file.

2. Creating a Firebase Project

In order to integrate your Flutter application with the Firebase Platform, first you have to create a Firebase Project. And here are the steps.

  1. Go to the Firebase Console.

  2. Click on the big Add project button.

  1. Enter your Project name.
  • I used hello-world for this example. Firebase automatically appends a unique ID to your project name — for example, the project I created ended up with the name hello-world-f2206.
  1. You can pick a Cloud Firestore Location.
  • I used hello-world for this example. Firebase automatically appends a unique ID to your project name — for example, the project I created ended up with the name hello-world-f2206.
  1. Accept the Terms and Conditions.

  1. Once you are done, scroll to the bottom and click Create Project.

  • I used hello-world for this example. Firebase automatically appends a unique ID to your project name — for example, the project I created ended up with the name hello-world-f2206.

Firebase will take some time to ready your application. Once done, click on the Continue button to open up the Firebase Project Overview Page.

4. Configure an iOS Application

  1. In your Firebase Project Overview Page, launch the setup wizard for iOS.

  1. Inside the setup wizard, put in the iOS bundle ID. The Register app button should then light up, click on it.
  • I used hello-world for this example. Firebase automatically appends a unique ID to your project name — for example, the project I created ended up with the name hello-world-f2206.

  1. Download the GoogleService-Info.plist configuration file and put it into the iOS Project root folder, then click Next.
  • I used hello-world for this example. Firebase automatically appends a unique ID to your project name — for example, the project I created ended up with the name hello-world-f2206.

  1. Follow the instructions to add the Firebase SDK, then click Next.

  • I used hello-world for this example. Firebase automatically appends a unique ID to your project name — for example, the project I created ended up with the name hello-world-f2206.
  1. Modify the code inside the main AppDelegate as instructed by the setup wizard then click Next. For this example, I used Objective-C, and therefore replaced the contents inside AppDelegate.m with the following code.
#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"

@import UIKit;
@import Firebase;

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[FIRApp configure];
return YES;
}

@end

  1. Get back to the root folder and run your app, after a while you should see the setup wizard showing that your app is added to Firebase. Click Continue to the Console to finish the setup.

Congratulations! You have successful added Firebase to your Flutter application. Despite the fact that having both Firebase and Flutter from Google is supper cool, it is actually a good Software Engineering practice to always have a plan B, as well as plan C, D,E, F, and G. In the future I will write another guide on an example application utilizing Firebase, and more on Flutter.

Have fun coding!!!

Appendices:

3.1 Switching to Administrator Account

If you ran into the following message, it means that you need to contact the organization of your Gmail account to grant you access to Google Developers Console.

4.1 Finding iOS Project root folder & Acquiring Bundle ID

  1. Launch Xcode from the Launchpad.

  2. Select “Open another project…” at the bottom of the prompt screen.

  1. Navigate to your Flutter project folder, open the “ios” folder and select “Runner.xcodeproj”. This should automatically open up the project in Xcode.

  1. Select the Runner project on the left, you should now see the Bundle Identifier under Identity.

4.2 Installing CocoaPods and Firebase SDK

In case the instructions inside the setup wizard did not work out, you will have to remove the existing Podfile in order to reinstall them correctly.

  1. CocoaPods is built with Ruby and is installable with the default Ruby available on MacOS. Use the following commands to install it.
sudo gem install cocoapods

  1. Initialize the Podfile with the following command.
pod init

  1. Then, add the following code to the initialized Podfile.
pod 'Firebase/Core'

  1. Once done, save the changes made to the Podfile, and install the Firebase SDK with the following command.
pod install

  1. After the installation, you will likely have to configure the .xcconfig files. First you will have to copy the files from the Pods/Target Support Files/Pods-Runner folder to Flutter folder.

  1. Then you will have to include them into the Debug.xcconfig and Release.xcconfig files inside the Flutter folder.

In Debug.xcconfig:

#include "Pods-Runner.debug.xcconfig"

In Release.xcconfig:

#include "Pods-Runner.profile.xcconfig"
#include "Pods-Runner.release.xcconfig"

Build a CRUD app using Firebase and Flutter (Provider)

Build a CRUD app using Firebase and Flutter (Provider)

In this article, I will be showing how to set up and build a CRUD app using Firebase and a state management package called Provider that was announced by the Flutter team at Google I/O 2019.

Introduction

I am going to spend some time with the project set up to keep things well organized and easy to maintain in the future.

I am intending to make this into an episode-based tutorial so I will add in other parts things like File Upload using Firebase cloud storage and Smart Push Notifications

So, let’s get started.

What we are building

In this tutorial, we will build an app where you can different types of products and show these products in the main view.

Our final app will look like this:

Prerequisites

In order to follow this guide, you need the following:

  • Firebase console (usually linked with the Google account)
  • A Flutter project, e.g. course.productapp ( you need to decide on a project ID for your app using the following pattern <com>.<brand>.<app>. For example, the app would be com.course.productapp.)
  • iOS or ANDROID setup for the Flutter project
Project setup

Before diving into the real coding part, let’s see what are the plugins and assets required in this project.

Firebase console: Project setup

To get started with Firebase, you need to have a Google account. Visit https://firebase.google.com/ and log in with your Google account credentials. You will be logged in to the Firebase console where you need to set up your project. Once logged in you can create a project.

Now, let’s create our Demo project.

In the Firebase console clique add project and chose your project name

ANDROID SetupOnce the project is created, go to the Firebase Console and register your app by clicking Add Firebase to your app Android. Enter your project ID

Download the google-services.json file to the android/app directory

At this point, you can skip all remaining steps in the Firebase console (Flutter does this stuff automatically).Now we need to register our Google services in the Gradle build files under android/build.gradle

buildscript {

   dependencies {

       // ...

       classpath 'com.google.gms:google-services:4.2.0'   // <-- here

   }

}

Next, update your project ID and register the Google services plugin at the bottom of the gradle build file in the app directory.

defaultConfig {

        applicationId "com.course.product" // <-- update this line

        minSdkVersion 21 // <-- you might also need to change this to 21

        // ...

    }

// ... bottom of file

apply plugin: 'com.google.gms.google-services' // <-- add

That’s it. Our android app is ready to go

IOS Setup

The iOS setup is easier and can be completed in one step.

Click add your app to iOS then download the GoogleService-Info.plist file into the ios/Runner/Runnerdirectory from XCode (Make sure to use XCode ).

Plugins

The plugins needed for this project are:

1.cloud_firestore(A Flutter plugin to use the Cloud Firestore API.)

2.firebase_core( Flutter plugin for Firebase Core, enabling connecting to multiple Firebase apps.)

3.provider( A dependency injection system built with widgets for widgets. provider is mostly syntax sugar for InheritedWidget, to make common use-cases straightforward.)

4.get_it(we will use it for dependency injection with provider)

Don't forget to run flutter packages getAssets

we will need some images for this project which we will use for our product app. (you can find them in under the asset folder in the Github project)

Now . we should be ready to start coding.

Implementation

you can follow the setup project in Github under code_setup branch.

Code Setup

the architecture I am going to use was introduced by Dane Mackier so feel free to check his article Here

Let’s quickly go over the structure. The lib folder is divided into two folders. core and UI. Core contains all the files associated with the logic. UI contains all the files associated with the UI. Core is divided into three folders.

  • Models: Contains all the plain data models
  • Services: Contains the dedicated files that will handle actual business logic
  • ViewModels: Contains the Provider models for each of the Widget views

UI is also divided into three folders.

  • Shared: Contains files used in multiple other UI files
  • Views: Contains the files for the app views
  • Widgets: Contains widget files that are too big to keep in the view files.

we will not be providing a bunch of models and services at the beginning of our app at global context scale. Instead, we’ll inject it using the locator setup in locator.dart

So this is how our project will look

Step 1: Create model class

We’ll go through the app view by view and add what we need.

Our application will need a Product model so under models we will create productModel.dartfile.

This file contains 2 methods :

Product.fromMap(Map snapshot, String id): When data is fetched from Firebase, it is in JSON format. this method allows us to map data from JSON format to our Product format.

toJson() : The toJson() does the opposite which is to map the data back into JSON format before we upload into Firebase.

class Product {

  String id;

  String price;

  String name;

  String img;

  Product({this.id, this.price, this.name,this.img});

  Product.fromMap(Map snapshot,String id) :

        id = id ?? '',

        price = snapshot['price'] ?? '',

        name = snapshot['name'] ?? '',

        img = snapshot['img'] ?? '';

  toJson() {

    return {

      "price": price,

      "name": name,

      "img": img,

    };

  }

}

Step 2: Create Api class

Under our Services directory will perform all the Network work. we will Create an Api class that will request /Read/Delete/ update data from Firebase. That class will contain different methods like fetching data as a stream , getting the document by id, removing/deleting a document …

class Api{

  final Firestore _db = Firestore.instance;

  final String path;

  CollectionReference ref;

  Api( this.path ) {

    ref = _db.collection(path);

  }

  Future<QuerySnapshot> getDataCollection() {

    return ref.getDocuments() ;

  }

  Stream<QuerySnapshot> streamDataCollection() {

    return ref.snapshots() ;

  }

  Future<DocumentSnapshot> getDocumentById(String id) {

    return ref.document(id).get();

  }

  Future<void> removeDocument(String id){

    return ref.document(id).delete();

  }

  Future<DocumentReference> addDocument(Map data) {

    return ref.add(data);

  }

  Future<void> updateDocument(Map data , String id) {

    return ref.document(id).updateData(data) ;

  }

}

Now to hook it up. As mentioned we will not be providing a bunch of models and services at the beginning of our app at global context scale. Instead, we’ll inject it using the locator setup in locator.dart

void setupLocator() {

  locator.registerLazySingleton(() => Api('products'));

}

Step 3: Create CRUD Model

The CRUD Model will use the Api class to Handle the different operations. Under viewmodels create the CRUDModel.dart file and add the different functions needed. This model (as well as every other service and model) will be injected using the locator.

class CRUDModel extends ChangeNotifier {

  Api _api = locator<Api>();

  List<Product> products;

  Future<List<Product>> fetchProducts() async {

    var result = await _api.getDataCollection();

    products = result.documents

        .map((doc) => Product.fromMap(doc.data, doc.documentID))

        .toList();

    return products;

  }

  Stream<QuerySnapshot> fetchProductsAsStream() {

    return _api.streamDataCollection();

  }

  Future<Product> getProductById(String id) async {

    var doc = await _api.getDocumentById(id);

    return  Product.fromMap(doc.data, doc.documentID) ;

  }

  Future removeProduct(String id) async{

     await _api.removeDocument(id) ;

     return ;

  }

  Future updateProduct(Product data,String id) async{

    await _api.updateDocument(data.toJson(), id) ;

    return ;

  }

  Future addProduct(Product data) async{

    var result  = await _api.addDocument(data.toJson()) ;

    return ;

  }

}

Now we register it in the locator file.

void setupLocator() {

  locator.registerLazySingleton(() => Api('products'));

  locator.registerLazySingleton(() => CRUDModel()) ;

}

that should be all for the logic now we will move to creating our UI and consuming these services.

Step 4: Routing and main configuration

Our app will have 4 screens. To keep things nice and clean we’ll put all the routing in a separate file called router.dart under the UI folder his function receives RouteSettings which contains the name of the route being requested. We’ll also return an error view for any undefined route.

class Router {

  static Route<dynamic> generateRoute(RouteSettings settings) {

    switch (settings.name) {

      case '/' :

        return  MaterialPageRoute(

          builder: (_)=> HomeView()

        );

      case '/addProduct' :

        return MaterialPageRoute(

          builder: (_)=> AddProduct()

        ) ;

      case '/productDetails' :

        return MaterialPageRoute(

            builder: (_)=> ProductDetails()

        ) ;

      default:

        return MaterialPageRoute(

            builder: (_) => Scaffold(

              body: Center(

                child: Text('No route defined for ${settings.name}'),

              ),

            ));

    }

  }

}

now under the main file, we will provide the onGenerateRoute property with the static generateRoute function from the Router. You can remove the home property and set the initialRoute to '/' instead. and we will initialize our Provider parameters in the MultiProvider and setup our locator.

void main() {

  setupLocator();

  runApp(MyApp());

}

class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MultiProvider(

      providers: [

        ChangeNotifierProvider(builder: (_) => locator<CRUDModel>()),

      ],

      child: MaterialApp(

        debugShowCheckedModeBanner: false,

        initialRoute: '/',

        title: 'Product App',

        theme: ThemeData(),

        onGenerateRoute: Router.generateRoute,

      ),

    );

  }

}

Step 5: Creating Home Screen

In HomeView.dartwe will fetch different products from the collection products and display them in cards. Whenever the list of products is edited or a new product is added the stream will fetch it from Firebase with the help of our provider CRUDModeafter calling it, we will store it into local list variables List<Product> products and then display it.

class _HomeViewState extends State<HomeView> {

  List<Product> products;

  @override

  Widget build(BuildContext context) {

    final productProvider = Provider.of<CRUDModel>(context);

    return Scaffold(

      floatingActionButton: FloatingActionButton(

        onPressed: () {

          Navigator.pushNamed(context, '/addProduct');

        },

        child: Icon(Icons.add),

      ),

      appBar: AppBar(

        title: Center(child: Text('Home')),

      ),

      body: Container(

        child: StreamBuilder(

            stream: productProvider.fetchProductsAsStream(),

            builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {

              if (snapshot.hasData) {

                products = snapshot.data.documents

                    .map((doc) => Product.fromMap(doc.data, doc.documentID))

                    .toList();

                return ListView.builder(

                  itemCount: products.length,

                  itemBuilder: (buildContext, index) =>

                      ProductCard(productDetails: products[index]),

                );

              } else {

                return Text('fetching');

              }

            }),

      ),

    );

    ;

  }

}

Now we will create ProductCard() to display the details of the product:

import 'package:flutter/material.dart';

import 'package:productapp/core/models/productModel.dart';

import 'package:productapp/ui/views/productDetails.dart';

class ProductCard extends StatelessWidget {

  final Product productDetails;

  ProductCard({@required this.productDetails});

  @override

  Widget build(BuildContext context) {

    return GestureDetector(

      onTap: (){

        Navigator.push(context, MaterialPageRoute(builder: (_) => ProductDetails(product: productDetails)));

      },

      child: Padding(

        padding: EdgeInsets.all(8),

        child: Card(

          elevation: 5,

          child: Container(

            height: MediaQuery

                .of(context)

                .size

                .height * 0.45,

            width: MediaQuery

                .of(context)

                .size

                .width * 0.9,

            child: Column(

              children: <Widget>[

                Hero(

                  tag: productDetails.id,

                  child: Image.asset(

                    'assets/${productDetails.img}.jpg',

                    height: MediaQuery

                        .of(context)

                        .size

                        .height *

                        0.35,

                  ),

                ),

                Padding(

                  padding: EdgeInsets.all(16),

                  child: Row(

                    mainAxisAlignment:

                    MainAxisAlignment.spaceBetween,

                    children: <Widget>[

                      Text(

                        productDetails.name,

                        style: TextStyle(

                            fontWeight: FontWeight.w900,

                            fontSize: 22,

                            fontStyle: FontStyle.italic),

                      ),

                      Text(

                        '${productDetails.price} $',

                        style: TextStyle(

                            fontWeight: FontWeight.w900,

                            fontSize: 22,

                            fontStyle: FontStyle.italic,

                            color: Colors.orangeAccent),

                      ),

                    ],

                  ),

                )

              ],

            ),

          ),

        ),

      ),

    );

  }

}

Step 6: Creating Product details and add product Screens

to create a new Product item, we will take the name input and price by the user . We instantiate a new Product object using our Finally we upload to Firebase using our addProduct() function called using the CRUD provider

Scaffold(

  appBar: AppBar(),

  body: Padding(

    padding: EdgeInsets.all(12),

    child: Form(

      key: _formKey,

      child: Column(

        children: <Widget>[

          TextFormField(

            decoration: InputDecoration(

              border: InputBorder.none,

              hintText: 'Product Title',

              fillColor: Colors.grey[300],

              filled: true,

            ),

            validator: (value) {

              if (value.isEmpty) {

                return 'Please enter Product Title';

              }

            },

              onSaved: (value) => title = value

          ),

          SizedBox(height: 16,),

          TextFormField(

            keyboardType: TextInputType.numberWithOptions(),

            decoration: InputDecoration(

              border: InputBorder.none,

              hintText: 'Price',

              fillColor: Colors.grey[300],

              filled: true,

            ),

            validator: (value) {

              if (value.isEmpty) {

                return 'Please enter The price';

              }

            },

              onSaved: (value) => price = value

          ),

          DropdownButton<String>(

            value: productType,

            onChanged: (String newValue) {

              setState(() {

                productType = newValue;

              });

            },

            items: <String>['Bag', 'Computer', 'Dress', 'Phone','Shoes']

                .map<DropdownMenuItem<String>>((String value) {

              return DropdownMenuItem<String>(

                value: value,

                child: Text(value),

              );

            }).toList(),

          ),

          RaisedButton(

            splashColor: Colors.red,

            onPressed: () async{

              if (_formKey.currentState.validate()) {

                _formKey.currentState.save();

                await productProvider.addProduct(Product(name: title,price: price,img: productType.toLowerCase()));

                Navigator.pop(context) ;

              }

            },

            child: Text('add Product', style: TextStyle(color: Colors.white)),

            color: Colors.blue,

          )

        ],

      ),

    ),

  ),

);

Now to delete or update a product we will add another screen to check for the product details and from there we can either delete it or change it

class ProductDetails extends StatelessWidget {

  final Product product;

  ProductDetails({@required this.product});

  @override

  Widget build(BuildContext context) {

    final productProvider = Provider.of<CRUDModel>(context);

    return Scaffold(

      appBar: AppBar(

        title: Text('Product Details'),

        actions: <Widget>[

         

          IconButton(

            iconSize: 35,

            icon: Icon(Icons.delete_forever),

            onPressed: ()async {

              await productProvider.removeProduct(product.id);

              Navigator.pop(context) ;

            },

          ),

          IconButton(

            iconSize: 35,

            icon: Icon(Icons.edit),

            onPressed: (){

              Navigator.push(context, MaterialPageRoute(builder: (_)=> ModifyProduct(product: product,)));

            },

          )

        ],

      ),

      body: Column(

        mainAxisSize: MainAxisSize.max,

        crossAxisAlignment: CrossAxisAlignment.center,

        children: <Widget>[

          Hero(

            tag: product.id,

            child: Image.asset(

              'assets/${product.img}.jpg',

              height: MediaQuery.of(context).size.height * 0.35,

              width: MediaQuery.of(context).size.width,

            ),

          ),

          SizedBox(

            height: 20,

          ),

          Text(

            product.name,

            style: TextStyle(

                fontWeight: FontWeight.w900,

                fontSize: 22,

                fontStyle: FontStyle.italic),

          ),

          Text(

            '${product.price} $',

            style: TextStyle(

                fontWeight: FontWeight.w900,

                fontSize: 22,

                fontStyle: FontStyle.italic,

                color: Colors.orangeAccent),

          )

        ],

      ),

    );

  }

}

That’s all our app Should Be ready to rock .

Github

Source code available

Final Thoughts

I hope this helped. There are many other things to add on, but this is where you want to start. I am intending to add other functionalities in the future instead of fetching the photos locally we will store it in Firebase storage or adding Firebase ML Kit to recognize the product details and give more information about it

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Learn Flutter & Dart to Build iOS & Android Apps

Flutter & Dart - The Complete Flutter App Development Course

Dart and Flutter: The Complete Developer’s Guide

Flutter - Advanced Course

Flutter Tutorial - Flight List UI Example In Flutter

Flutter Tutorial for Beginners - Full Tutorial

Using Go Library in Flutter

A Beginners Guide to the Flutter Bottom Sheet

Flutter Course - Full Tutorial for Beginners (Build iOS and Android Apps)

Flutter Tutorial For Beginners - Build Your First Flutter App

Building the SwiftUI Sample App in Flutter

Building Cryptocurrency Pricing App with Flutter


Flutter Tutorial for Beginners - Build Android and iOS Apps with a Flutter Framework

Build Android and iOS apps with a flutter framework


You’ll learn

  • Better understanding of flutter and it’s basic widgets
  • Develop basic flutter application for android and iOS


Thanks for watching

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Learn Flutter & Dart to Build iOS & Android Apps

Flutter & Dart - The Complete Flutter App Development Course

Dart and Flutter: The Complete Developer’s Guide

Flutter - Advanced Course

Flutter Tutorial - Flight List UI Example In Flutter

Flutter Tutorial for Beginners - Full Tutorial

Using Go Library in Flutter

Parsing JSON in Flutter

Flutter Tutorial - Build iOS & Android App with Google Flutter & Dart

Flutter Tutorial - Build iOS & Android App with Google Flutter & Dart

In this Flutter Tutorial for Beginners, you will learn how to build iOS & Android apps with Google Flutter and Dart

In this post, Flutter Tutorial for Beginners; you will learn how to build iOS & Android apps with Googles Flutter and Dart.

You don't need to learn Android/ Java and iOS/ Swift development to build real native mobile apps!

Flutter - a framework developed by Google - allows you to learn one language (Dart) and build beautiful native mobile apps in no time. Flutter is a SDK providing the tooling to compile that Dart code into native code and it also gives you a rich set of pre-built and pre-styled UI elements (so called widgets) which you can use to compose your user interfaces!

Let's get started in this video!

Take the full course on Udemy at a discount with the following link: http://bit.ly/2O5EaKu