Install :
http: ^1.2.1
Examples:
import 'package:flutter/material.dart';
import 'dart:convert'; // convert json to String
import 'package:http/http.dart' as http; // http is use
class HttpFlutter extends StatefulWidget {
const HttpFlutter({super.key});
@override
State<HttpFlutter> createState() => _HttpFlutterState();
}
class _HttpFlutterState extends State<HttpFlutter> {
dynamic data; // main data store every thing
Future getData() async {
var res =
await http.get(Uri.parse('https://aponali.github.io/api/allapon.json')); // apiUrl
setState(() {
var decode = json.decode(res.body); // decode json
data = decode;
// print(data);
});
}
@override
void initState() {
super.initState();
getData(); // it's important other wise it data not show screen
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: data == null ? 0 : data.length, // length the list and data if null show 0
itemBuilder: (context, index) {
return Text(data[index]["allappname"]);
},
),
);
}
}
GET Requests:
Future<http.Response> fetchUsers() async {
final response = await http.get(Uri.parse('https://api.example.com/users'));
if (response.statusCode == 200) {
// Request was successful
return response;
} else {
// Request failed
throw Exception('Failed to load users');
}
}
POST Requests:
Future<http.Response> createUser(String name, int age) async {
final response = await http.post(
Uri.parse('https://api.example.com/users'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, dynamic>{
'name': name,
'age': age,
}),
);
if (response.statusCode == 201) {
// User created successfully
return response;
} else {
// Request failed
throw Exception('Failed to create user');
}
}
PUT Requests:
Future<http.Response> updateUser(int id, String newName) async {
final response = await http.put(
Uri.parse('https://api.example.com/users/$id'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, dynamic>{
'name': newName,
}),
);
if (response.statusCode == 200) {
// User updated successfully
return response;
} else {
// Request failed
throw Exception('Failed to update user');
}
}
DELETE Requests:
Future<http.Response> deleteUser(int id) async {
final response = await http.delete(
Uri.parse('https://api.example.com/users/$id'),
);
if (response.statusCode == 204) {
// User deleted successfully
return response;
} else {
// Request failed
throw Exception('Failed to delete user');
}
}
