Firebase: API Integration In Flutter Using Firebase (Real-time Database)
API integration in firebase
1: Prepare Json Data
2: Firebase (Real-time Database) setup
3: Model Class
4: API Method
5: Main UI to Show Data
To integrate an API in Flutter using a real-time database, you can follow these steps:
#Step 1: Prepare Json Data
Before we go ahead first we need to prepare Json Data using notepad or any other editor
Square Bracket [ ]
Curly Braces { }
[ {}, {}, {} ]
[
{data1},
{data2},
{data3}
]
Let’s prepare the data
[
{
“id”: “1”,
“name”: “John”,
“job”: “Software engineer”
},
{
“id”: “2”,
“name”: “Ali”,
“job”: “Freelancer”
},
{
“id”: “3”,
“name”: “Riax”,
“job”: “IT”
}
]
Save it with extention .json
I’m saving the file with file.json
Import the file in Firebase,
let’s do it.
#Step 2: Firebase (Real-time Database) setup
Open Firebase website and login with your Gmail account
Now click on add project as mentioned below:
Name your project: I have written test for testing purpose and click continue
I skipped few steps like analytics etc.
Setup is complete now lets add Real-time Database as mentioned below:
Click on Build >Realtime Database > Create Database
Click Create Database > Select Location > Start In Test Mode(for test) or Locked Mode(for real app) > Enable.
The UI will look like this as mentioned below:
We will access this link in our coding part.
Click on Pen (edit) Icon and write your table name for accessing data:
as I have written /mydata hit enter
Name your table here I have written mydata now import the file where we created it.
1: Name it, 2: Import the file.
After importing the file (if there is no error in Json format) it will look like this.
Let’s access this via web.
YourLinkName/mydata.json as you can see the data below:
#Step 3: Model Class
What we have added in Firebase as an id, name and job write the same in model class to access them.
class ModelClass
{
String id;
String name;
String job;
ModelClass({
required this.id,
required this.name,
required this.job
});
factory ModelClass.fromMap(Map<String, dynamic> toJson){
return ModelClass(
id: toJson['id'],
name: toJson['name'],
job: toJson['job']);
}
}
#Step 4: API Method
First add http: ^0.13.5 package to pubspec.yaml, current version is 0.13.5, you may see different version.
import 'dart:convert';
import 'package:testproject/model/model.dart';
import 'package:http/http.dart' as http;
class APIService
{
final String baseURL = 'test-e2456-default-rtdb.asia-southeast1.firebasedatabase.app';
Future<List<ModelClass>> getAPI() async
{
final response = await http.get(Uri.https(baseURL, 'mydata.json'));
List body = jsonDecode(response.body);
List<ModelClass> _list = [];
body.forEach((element) {
_list.add(ModelClass.fromMap(element));
});
return _list;
}
}
Explanation: Copy the Firebase URL where we have created and stored the data
Note: Remove the http:// part and store the link in baseURL.
final String baseURL = 'test-e2456-default-rtdb.asia-southeast1.firebasedatabase.app';
Call the baseURL link and table name with .json e.g mydata.json
final response = await http.get(Uri.https(baseURL, 'mydata.json'));
#Step 5: Main UI to Show The Data
clean the code in main.dart lets start from scratch but inside widget_test.dart remove the one line or comment it.
Alright, now it’s time to write the main method to show the data:
Full Code: In main.dart
import '/api/api.dart';
import '/model/model.dart';
import 'package:flutter/material.dart';
void main()
{
runApp(
MaterialApp(
home: TestClass(),
)
);
}
class TestClass extends StatefulWidget {
const TestClass({Key? key}) : super(key: key);
@override
State<TestClass> createState() => _TestClassState();
}
class _TestClassState extends State<TestClass> {
late Future<List<ModelClass>> _modelCLass;
late APIService _apiService;
@override
void initState() {
// TODO: implement initState
super.initState();
fetchData();
}
void fetchData() async
{
_apiService = APIService();
_modelCLass = _apiService.getAPI();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: _modelCLass,
builder: (context, snapShot){
if(snapShot.hasData)
{
return ListView.builder(
itemCount: snapShot.data!.length,
itemBuilder: (context, index){
final allData = snapShot.data![index];
return ListTile(
title: Text(allData.name),
subtitle: Text(allData.job),
leading: Text(allData.id),
);
});
}else if(snapShot.hasError)
{
print('${snapShot.error}');
return Text('${snapShot.error}');
}else
{
return Center(child: CircularProgressIndicator(),);
}
},
),
);
}
}
Here is the final result:
If this really helped you please follow and like the article, thank you.