In this post, you will learn about firebase realtime database crud operation for flutter project.
The Firebase realtime database is NoSQL, which means we don’t have the traditional columns and rows.
In the firebase realtime database we can store data in JSON tree structure like below.
In this post we will create an app in which we will perform the CRUD operation of firebase realtime database (Create, Read, Update and Delete).
Firebase Realtime Database CRUD Operations in Flutter
First of all, create a new flutter project and connect it with firebase to use
firebase realtime database in your project.
Below is the detailed video tutorial of How to connect flutter project with firebase.
After this open your pubspec.yaml file and add the below dependencies.
1 2 3 4 5 6 7 8 9 10 11 12 |
dependencies: flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.2 firebase_database: ^9.0.20 firebase_core: ^1.20.0 |
Now create a directory inside lib and name it screens, then creates 3 dart files in the screens directory.
- fetch_data.dart
- insert_data.dart
- update_record.dart
Now start coding the application.
main.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter_firebase_series/screens/fetch_data.dart'; import 'package:flutter_firebase_series/screens/insert_data.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); Firebase.initializeApp(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Flutter Firebase'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ const Image( width: 300, height: 300, image: NetworkImage( 'https://seeklogo.com/images/F/firebase-logo-402F407EE0-seeklogo.com.png'), ), const SizedBox( height: 30, ), const Text( 'Firebase Realtime Database Series in Flutter 2022', style: TextStyle( fontSize: 24, fontWeight: FontWeight.w500, ), textAlign: TextAlign.center, ), const SizedBox( height: 30, ), MaterialButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => const InsertData())); }, child: const Text('Insert Data'), color: Colors.blue, textColor: Colors.white, minWidth: 300, height: 40, ), const SizedBox( height: 30, ), MaterialButton( onPressed: () { Navigator.push(context, MaterialPageRoute(builder: (context) => const FetchData())); }, child: const Text('Fetch Data'), color: Colors.blue, textColor: Colors.white, minWidth: 300, height: 40, ), ], ), ), ); } } |
insert_data.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
import 'package:firebase_database/firebase_database.dart'; import 'package:flutter/material.dart'; class InsertData extends StatefulWidget { const InsertData({Key? key}) : super(key: key); @override State<InsertData> createState() => _InsertDataState(); } class _InsertDataState extends State<InsertData> { final userNameController = TextEditingController(); final userAgeController= TextEditingController(); final userSalaryController =TextEditingController(); late DatabaseReference dbRef; @override void initState() { super.initState(); dbRef = FirebaseDatabase.instance.ref().child('Students'); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Inserting data'), ), body: Center( child: Padding( padding: EdgeInsets.all(8.0), child: Column( children: [ const SizedBox( height: 50, ), const Text( 'Inserting data in Firebase Realtime Database', style: TextStyle( fontSize: 24, fontWeight: FontWeight.w500, ), textAlign: TextAlign.center, ), const SizedBox( height: 30, ), TextField( controller: userNameController, keyboardType: TextInputType.text, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Name', hintText: 'Enter Your Name', ), ), const SizedBox( height: 30, ), TextField( controller: userAgeController, keyboardType: TextInputType.number, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Age', hintText: 'Enter Your Age', ), ), const SizedBox( height: 30, ), TextField( controller: userSalaryController, keyboardType: TextInputType.phone, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Salary', hintText: 'Enter Your Salary', ), ), const SizedBox( height: 30, ), MaterialButton( onPressed: () { Map<String, String> students = { 'name': userNameController.text, 'age': userAgeController.text, 'salary': userSalaryController.text }; dbRef.push().set(students); }, child: const Text('Insert Data'), color: Colors.blue, textColor: Colors.white, minWidth: 300, height: 40, ), ], ), ), ), ); } } |
fetch_data.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
import 'package:firebase_database/firebase_database.dart'; import 'package:firebase_database/ui/firebase_animated_list.dart'; import 'package:flutter/material.dart'; import 'package:flutter_firebase_series/screens/update_record.dart'; class FetchData extends StatefulWidget { const FetchData({Key? key}) : super(key: key); @override State<FetchData> createState() => _FetchDataState(); } class _FetchDataState extends State<FetchData> { Query dbRef = FirebaseDatabase.instance.ref().child('Students'); DatabaseReference reference = FirebaseDatabase.instance.ref().child('Students'); Widget listItem({required Map student}) { return Container( margin: const EdgeInsets.all(10), padding: const EdgeInsets.all(10), height: 110, color: Colors.amberAccent, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( student['name'], style: TextStyle(fontSize: 16, fontWeight: FontWeight.w400), ), const SizedBox( height: 5, ), Text( student['age'], style: TextStyle(fontSize: 16, fontWeight: FontWeight.w400), ), const SizedBox( height: 5, ), Text( student['salary'], style: TextStyle(fontSize: 16, fontWeight: FontWeight.w400), ), Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.center, children: [ GestureDetector( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (_) => UpdateRecord(studentKey: student['key']))); }, child: Row( children: [ Icon( Icons.edit, color: Theme.of(context).primaryColor, ), ], ), ), const SizedBox( width: 6, ), GestureDetector( onTap: () { reference.child(student['key']).remove(); }, child: Row( children: [ Icon( Icons.delete, color: Colors.red[700], ), ], ), ), ], ) ], ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Fetching data'), ), body: Container( height: double.infinity, child: FirebaseAnimatedList( query: dbRef, itemBuilder: (BuildContext context, DataSnapshot snapshot, Animation<double> animation, int index) { Map student = snapshot.value as Map; student['key'] = snapshot.key; return listItem(student: student); }, ), ) ); } } |
update_record.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
import 'package:firebase_database/firebase_database.dart'; import 'package:flutter/material.dart'; class UpdateRecord extends StatefulWidget { const UpdateRecord({Key? key, required this.studentKey}) : super(key: key); final String studentKey; @override State<UpdateRecord> createState() => _UpdateRecordState(); } class _UpdateRecordState extends State<UpdateRecord> { final userNameController = TextEditingController(); final userAgeController= TextEditingController(); final userSalaryController =TextEditingController(); late DatabaseReference dbRef; @override void initState() { super.initState(); dbRef = FirebaseDatabase.instance.ref().child('Students'); getStudentData(); } void getStudentData() async { DataSnapshot snapshot = await dbRef.child(widget.studentKey).get(); Map student = snapshot.value as Map; userNameController.text = student['name']; userAgeController.text = student['age']; userSalaryController.text = student['salary']; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Updating record'), ), body: Center( child: Padding( padding: EdgeInsets.all(8.0), child: Column( children: [ const SizedBox( height: 50, ), const Text( 'Updating data in Firebase Realtime Database', style: TextStyle( fontSize: 24, fontWeight: FontWeight.w500, ), textAlign: TextAlign.center, ), const SizedBox( height: 30, ), TextField( controller: userNameController, keyboardType: TextInputType.text, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Name', hintText: 'Enter Your Name', ), ), const SizedBox( height: 30, ), TextField( controller: userAgeController, keyboardType: TextInputType.number, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Age', hintText: 'Enter Your Age', ), ), const SizedBox( height: 30, ), TextField( controller: userSalaryController, keyboardType: TextInputType.phone, decoration: const InputDecoration( border: OutlineInputBorder(), labelText: 'Salary', hintText: 'Enter Your Salary', ), ), const SizedBox( height: 30, ), MaterialButton( onPressed: () { Map<String, String> students = { 'name': userNameController.text, 'age': userAgeController.text, 'salary': userSalaryController.text }; dbRef.child(widget.studentKey).update(students) .then((value) => { Navigator.pop(context) }); }, child: const Text('Update Data'), color: Colors.blue, textColor: Colors.white, minWidth: 300, height: 40, ), ], ), ), ), ); } } |
So guys at this point our tutorial is completed and in the above steps we
performed the CRUD operations of Firebase Realtime Database.
Happy Coding…
D:/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core-1.24.0/lib/src/firebase_app.dart:18:25: Error: Member not found: ‘FirebaseAppPlatform.verifyExtends’.
FirebaseAppPlatform.verifyExtends(_delegate);
^^^^^^^^^^^^^