API Integration In Flutter With Model Class

Mr Riax
2 min readApr 1, 2023

--

These are the three elements will be implemented:

1: Model Class

2: HTTP Package and Method

3: Main UI to Show Data

1: Model Class

Class name ModelClass with two instance variable title & body, another model class

class ModelClass {
String title;
String body;

ModelClass({
required this.title,
required this.body
});

factory ModelClass.fromMap(Map<String, dynamic> json) {
return ModelClass(
title: json['title'],
body: json['body']);
}
}

factory ModelClass.fromMap(Map<String, dynamic> json)
{ return ModelClass(
title: json[‘title’],
body: json[‘body’]);
}

factory is used to return data where we have returned model class adn assigned map json

2: HTTP Package and Method

First add http: ^0.13.5 package to pubspec.yaml

import 'dart:convert';
import 'package:api_test/model/model.dart';
import 'package:http/http.dart' as http;
class APIService
{
Future<List<ModelClass>> getAPI() async
{
final url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
final response = await http.get(url);
List body = jsonDecode(response.body);
List<ModelClass> _list = [];
body.forEach((element) {
_list.add(ModelClass.fromMap(element));
});
return _list;
}
}

Class name APIService and method getAPI() where jsonplaceholder link is assigned to url now add http.get(url) to assign this data to response variable, here I have created list type variable of body and decode the data using jsonDecode(response.body), we have data in body.

I have created an empty list of model class type List<ModelClass> _list = [];

Here in body we have data now assign this data to empty list using forEach (You can use Map as well) method.

body.forEach((element) {
_list.add(ModelClass.fromMap(element));
});

As we know so far out data is in body and using forEach loop every element is fetched from body to element variable and adding this data to ModelClass.fromMap(element) as we created earlier.

4: Main UI to Show Data

We have two reference of ModelClass and APISerive to the fetch the data as mentioned below:

late Future<List<ModelCLass>> _modelCLass;
late APIService _apiService;

Now create a method fetchData() to initialize the references.

void fetchData() async
{
_apiService = APIService();
_modelCLass = _apiService.getAPI();
}

We have fetchData() method now add initState method to call fetchData to initialize these references.

@override
void initState() {
// TODO: implement initState
super.initState();
fetchData();
}

Here I’m using Future Builder and in future: add _modelClass now we have all the data inside snapShot and to check whether the data is fetched from the network or not use if(snapShot.hasData) if yes then run ListviewBuilder else run CircularProgressBar().

Inside ListViewBuilder() check the length of snapShot using snapShot.data!.length and in index we have length of data.

Below is Complete Code:

import 'package:api_test1/api/api.dart';
import 'package:api_test1/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){
return Text(snapShot.data![index].title);
});
}else
{
return Center(child: CircularProgressIndicator(),);
}
},
),
);
}
}

If this example really helped you feel free to like and I will publish API Integration using Firebase.

--

--

No responses yet