[Flutter] CRUD Firebase Realtime Database

Create “dbRef” object to work with Firebase database and RaisedButton for testing functions.

import 'package:firebase_database/firebase_database.dart';final dbRef = FirebaseDatabase.instance.reference();RaisedButton(
child: Text('Create Record'),
onPressed: () {
createRecord();
},
),

1. Create

Here we could use “set” or “update”, both are OK

void createRecord() async {
dbRef.child('students/ABLE1-9999').set({
'name' : 'Nguyễn Thanh Bình',
'token': [null, '9999']
});
}

Output

2. Read

2.1 Read all database

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

2.2 Read all childs

class Student {
String id;
String name;
String dob;
String allInfo;
Student(this.id, this.name, this.dob, this.allInfo);
}
List<Student> studentList = <Student>[];void readAllChild() async {
studentList.clear();
await dbRef.child('students')
.once().then((DataSnapshot snapshot) {
print('Data : ${snapshot.value}');
Map<dynamic, dynamic> values = snapshot.value; print('Loop all returned data to extract values...');
values.forEach((k, v) {
print('Student id =' + k);
print('Student info =' + v.toString());
print('Student info -> name =' + v['name']);
Student student = Student(k, v['name'], v['dob'], v.toString());
studentList.add(student);
});
print('studentList.length=' + studentList.length.toString());
});
}

Output

2.3 Read a particular child

void readRecord() async {
await dbRef.child('students/ABLE1-2021')
.once().then((DataSnapshot snapshot) {
print('Data : ${snapshot.value}');
String name = snapshot.value['name'].toString();
String token = snapshot.value['token'].toString();

print('name = ' + name);
print('token = ' + token);
List<dynamic> strTokenArr = snapshot.value['token'].toList();
print('Token[1] = ' + strTokenArr[1].toString());
});
}

Output

3. Update

void updateRecord() async {
//for array, we need to find & store it into List firstly
List<dynamic> strTokenArr;
await dbRef.child('students/ABLE1-2021')
.once().then((DataSnapshot snapshot) {
print('Data : ${snapshot.value}');
//add new item to list
strTokenArr = snapshot.value['token'].toList();
strTokenArr.add('NewTokenHere');
});
//update data
dbRef.child('students/ABLE1-2021').update({
'name': 'Nguyễn Thanh Bình new', //update string
'token': strTokenArr //update array
});
}

Output

4. Delete

void deleteRecord(){
dbRef.child('students/ABLE1-9999').remove();
}

5. Listen changes on realtime databse with StreamBuilder & FutureBuilder

Demo Code

“Developer never die” 😎🇻🇳