How to use Firebase with Flutter

Written by rajeev47Billion | Published 2018/10/31
Tech Story Tags: firebase-and-flutter | flutter | programming | ios | firebase

TLDRvia the TL;DR App

This article shows all the steps required to to build a skeleton app in Flutter with Firebase.

Google’s Flutter SDK can be used to develop apps that give native UI experience for both Android and iOS platforms. To write apps using Flutter, you have to use Dart programming language.

Firebase Realtime Database is a cloud-hosted database with data stored as JSON. It provides backend database with secure access to build rich, collaborative applications directly from the client-side. Data is persisted locally on the device while offline and realtime events continue to fire giving responsive experience to the end user. When the device regains connection to the internet, the realtime backend database is automatically synchronized with local data changes that occurred while the client was offline while auto-merging any conflicts.

Create FirebaseĀ Project

  1. Create a firebase project in firebaseĀ console.

https://console.firebase.google.com

2. Complete platform specific configuration

iOS

  • Register IOS app to firebase, iOS bundle Id must be same in Xcode project and on firebaseĀ console.

  • Download configuration files for your app and add it to your projectĀ folder.

  • Add firebase dependencies to yourĀ project

Android

  • Register you android app. Use package name in the project on firebaseĀ console.

  • Download the config file GoogleService-Info.plist and put it in the app module root directory.

Create FlutterĀ project

  1. Use the flutter create command to create a newĀ project.

    $ flutter create flutter_with_firebase

2. Open ios/Runner.xcworkspace. Keep same Bundle Identifier in xcode project as defined on the firebase console and save GoogleService-info.plist in RunnerĀ folder

3. In your IDE or editor, open the file pubspec.yaml. Add dependency for firebase_database and save theĀ file.

dependencies:
  flutter:
    sdk: flutter
  firebase_database: 1.0.3

4. In your IDE or command line with its current directory set to your Flutter app directory, run the following command.

flutter packagesĀ get

Setup

  1. Import dependency for firebase.

    import 'package:firebase_database/firebase_database.dart';

2. Create databaseReference object to work with database.

final databaseReference = FirebaseDatabase.instance.reference();

3. Create a screen with 4Ā buttons.

Create Record

1. On click of ā€œCreate Recordā€ button, createRecord() method isĀ invoked.

RaisedButton(
    child: Text('Create Record'),
    onPressed: () {
      createRecord();
    },
),

2. In createRecord(), we create two demo records in database.

void createRecord(){
  databaseReference.child("1").set({
    'title': 'Mastering EJB',
    'description': 'Programming Guide for J2EE'
  });
  databaseReference.child("2").set({
    'title': 'Flutter in Action',
    'description': 'Complete Programming Guide to learn Flutter'
  });
}

View Records

  1. On click of ā€œView Recordā€ button, getData() method isĀ invoked.

    RaisedButton( child: Text('View Record'), onPressed: () { getData(); }, )

2. In getData(), we retrieve all records from database.

void getData(){
  databaseReference.once().then((DataSnapshot snapshot) {
    print('Data : ${snapshot.value}');
  });
}

3. They are printed onĀ console

Data : [{title: Mastering EJB, description: Programming Guide for J2EE}, {title: Flutter in Action, description: Complete Programming Guide to learn Flutter}]

Update Record

  1. On click of ā€œUpdate Recordā€ button, updateData() method isĀ invoked.

    void updateData(){ databaseReference.child('1').update({ 'description': 'J2EE complete Reference' }); }

2. It updates description of title ā€˜Mastering EJB’ from ā€˜Programming Guide for J2EE’ to ā€˜J2EE complete Reference’

Delete Record

  1. On click of ā€œDelete Recordā€ button, deleteData() method isĀ invoked.

    void deleteData(){ databaseReference.child('1').remove(); }

2. It deletes record from the database.

Complete Code

import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';

class FirebaseDemoScreen extends StatelessWidget {

  final databaseReference = FirebaseDatabase.instance.reference();

  @override
  Widget build(BuildContext context) {
    getData();
    return Scaffold(
        appBar: AppBar(
            title: Text('Firebase Connect'),
            ),
        body: Center(
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[

                  RaisedButton(
                      child: Text('Create Record'),
                      onPressed: () {
                        createRecord();
                      },
                  ),

                  RaisedButton(
                      child: Text('View Record'),
                      onPressed: () {
                        getData();
                      },
                  ),
                  RaisedButton(
                      child: Text('Udate Record'),
                      onPressed: () {
                        updateData();
                      },
                  ),
                  RaisedButton(
                      child: Text('Delete Record'),
                      onPressed: () {
                        deleteData();
                      },
                  ),
                ],
            )
        ), //center
    );
  }

  void createRecord(){
    databaseReference.child("1").set({
      'title': 'Mastering EJB',
      'description': 'Programming Guide for J2EE'
    });
    databaseReference.child("2").set({
      'title': 'Flutter in Action',
      'description': 'Complete Programming Guide to learn Flutter'
    });
  }
  void getData(){
    databaseReference.once().then((DataSnapshot snapshot) {
      print('Data : ${snapshot.value}');
    });
  }

  void updateData(){
    databaseReference.child('1').update({
      'description': 'J2EE complete Reference'
    });
  }

  void deleteData(){
    databaseReference.child('1').remove();
  }
}

Thanks for reading. If you enjoyed this article, feel free to hit that clap button šŸ‘ to help others findĀ it.

This article is a part of the series of articles related to mobile technology. If you are looking for a Mobile app development team to build your solution, please contact us at [email protected].


Published by HackerNoon on 2018/10/31