Flutter - Fetch data from Json file using HTTP
In this article we will learn how to fetch data from the internet or JSON file using HTTP package in flutter
What is HTTP ?
A composable, Future-based library for making HTTP requests.
This package contains a set of high-level functions and classes that make it easy to consume HTTP resources. It's multi-platform, and supports mobile, desktop, and the browser.
so let's start
I hope you already know how to make a project in flutter, we will work in vs code .
The following steps are :
STEP 1 : Create a project in Vs code , And remove the default code .
STEP 2 : Before writing the code just add the HTTP plugin in your pubspec yaml file .
dependencies:
http: ^0.13.3
OR you can simply add your plugin from the terminal just type this command ,
flutter pub add http
After that run this command for getting the packages,
flutter pub get
STEP 3 : In main.dart file call the main() function , inside it run the runApp( ) method and give it an App (MyApp).
STEP 4 : Now create a stateful widget with the name 'MyApp' . A stateful widget is the widget that change their state during runtime , and return the MaterialApp( ) , MaterialApp has so much properties , but here we use only 2 or 3 , make the debugBanner false , tilte : "MyApi" , and in home property give a widget as you want , we give it MyApi( ),
import 'package:flutter/material.dart';
import 'package:workingwithhttp2/MyApi.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "MyApi",
debugShowCheckedModeBanner: false,
home: MyApi(),
);
}
}
Now let's create the class MyApi, you can work on same file but I am comfortable in work in different files for different task , so I create a new file MyApi.dart,
STEP 5 : In MyApi.dart file , make a stateful widget MyApi and return the scaffold , In scaffold there is a appBar and in appBar we have a title :"Geeks for Geeks " , in body we have a widget myApiWidget( ) ,
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class MyApi extends StatefulWidget {
MyApi({Key? key}) : super(key: key);
@override
_MyApiState createState() => _MyApiState();
}
class _MyApiState extends State<MyApi> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Geeks for Geeks"),
),
body: myApiWidget(),
);
}
}For data we have this JSON file,
STEP 6 : Now let's fetch this data using HTTP , create a function fetchUsers , and call the get function by http instances , It return the list of object .
Future<List<dynamic>> fetchUsers() async {
var result =
await http.get(Uri.parse("https://randomuser.me/api/?results=20"));
return jsonDecode(result.body)['results'];
}
STEP 7 : We have to call this Functioin fetchUers , But it is good to load data at initializing our APP , for that we have a init( ) method ,
@override
void initState() {
response = fetchUsers();
super.initState();
}Ohh great , we fetch the data successfully , now Its time to display it,
STEP 8 : create a myApiWidget() ,
myApiWidget() {
return FutureBuilder(
future: response,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Column(
children: [
ListTile(
title: Text(snapshot.data[index]['name']['title'] +
" " +
snapshot.data[index]['name']['first'] +
" " +
snapshot.data[index]['name']['last']),
trailing:
Text(snapshot.data[index]['dob']['age'].toString()),
leading: CircleAvatar(
backgroundImage: NetworkImage(
snapshot.data[index]['picture']['large'],
),
),
subtitle: Text(snapshot.data[index]['email']),
)
],
),
);
},
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
);
}
myApiWidget() {
return FutureBuilder(
future: response,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Column(
children: [
ListTile(
title: Text(snapshot.data[index]['name']['title'] +
" " +
snapshot.data[index]['name']['first'] +
" " +
snapshot.data[index]['name']['last']),
trailing:
Text(snapshot.data[index]['dob']['age'].toString()),
leading: CircleAvatar(
backgroundImage: NetworkImage(
snapshot.data[index]['picture']['large'],
),
),
subtitle: Text(snapshot.data[index]['email']),
)
],
),
);
},
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
);
}
Output : Here how we fetch the data using http package ,
Full code is available on github just check it .
Comments
Post a Comment