Hackernoon logoHow to use Firebase with Flutter by@rajeev47Billion

How to use Firebase with Flutter

image
Rajeev Dixit Hacker Noon profile picture

Rajeev Dixit

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

image

2. Complete platform specific configuration

image

iOS

  • Register IOS app to firebase, iOS bundle Id must be same in Xcode project and on firebase console.
image
  • Download configuration files for your app and add it to your project folder.
image
  • Add firebase dependencies to your project
image

Android

  • Register you android app. Use package name in the project on firebase console.
image
  • Download the config file GoogleService-Info.plist and put it in the app module root directory.
image

Create Flutter project

  1. Use the flutter create command to create a new project.
$ flutter create flutter_with_firebase
image

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

image

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.

image

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'
  });
}
image

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

image

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.

image

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].

image

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.