HTTP API calling in Flutter

Along with building a UI in Flutter, we can integrate it with the backend. Most of the application data is displayed on the mobile screen. We will use the HTTP package. REST API uses simple HTTP call and set JSON format,

When using HTTP while using async in flutter method so awaited for results and getting data from API. Those data sets in the list view of the Flutter application

  1. Awit & async features
  2. Provides various methods
  3. Provide class and HTTPS to perform web requests.

Let’s take an example of fetching data and setting it in the flutter list on the application.


Here is the step by step Implementation process:

Step 1 : Create a main.dart file in lib folder  and write below code .
 import 'package:flutter/material.dart';
import 'package:untitled/screen/home.dart';

void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}
Step 2 : Create a homescreen.dart file in lib folder and write below code. 
 import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});

@override
State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
List<dynamic> users = [];

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Rest API Call'),
),
//list view for set data
body: ListView.builder(
//set list of lenght
itemCount: users.length,
//set itembuilder
itemBuilder: (context, index) {
//user index data
final user = users[index];
//get name from response
final title = user['name']['first'];
//get email from response
final email = user['email'];
//get image from response
final imageUrl = user['picture']['thumbnail'];
return ListTile(
title: Text(title),
leading: ClipRRect(
borderRadius: BorderRadius.circular(100),
child: Image.network(imageUrl)),
subtitle: Text(email),
);
}),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
//click on flotting action button then call api
fetchData();
},
),
);
}

//fetch api and get response from network
Future<void> fetchData() async {
print("call api");
// url of network API
const url = 'https://randomuser.me/api/?results=100';
//url pass in parse method
final uri = Uri.parse(url);
//set uri in await method
final response = await http.get(uri);
//get body response
final body = response.body;
//json deconde
final json = jsonDecode(body);
setState(() {
//set reponse in users list
users = json['results'];
});
}
}

 

Step 3 : Output of above example


Happy coding!


365Bloggy May 27, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive