Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Making API Calls in Flutter

this is a flutter document

Uploaded by

engr.ahmadali99
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Making API Calls in Flutter

this is a flutter document

Uploaded by

engr.ahmadali99
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Making API calls in

Flutter
Shuja Akbar
Import the http Package

HTTP Package
• Add the http package to your pubspec.yaml file:

dependencies:
http: ^1.0.0

• Import the http Package


import 'package:http/http.dart' as http;
import 'dart:convert';
Making a GET Request
Future<void> fetchData() async {
final url =
Uri.parse('https://jsonplaceholder.typicode.com/pos
ts');
• http.get() is used to make a GET request.
• jsonDecode parses the JSON response into a try {
Dart object. final response = await http.get(url);
• Check response.statusCode to see if the request
was successful (status code 200 means if (response.statusCode == 200) {
success). final data = jsonDecode(response.body);
print('Data: $data');
} else {
print('Error: ${response.statusCode}');
}
} catch (e) {
print('An error occurred: $e');
}
}
Making a POST Request
Future<void> sendData() async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/posts');

final body = jsonEncode({


'title': 'Hello',
'body': 'This is a sample post',
'userId': 1,
• http.post() sends data to the specified URL. });
• headers specify the content type as application/json.
• body is the JSON-encoded data you want to send. try {
• A status code of 201 indicates successful creation of the final response = await http.post(
resource. url,
headers: {'Content-Type': 'application/json'},
body: body,
);

if (response.statusCode == 201) {
final data = jsonDecode(response.body);
print('Post created: $data');
} else {
print('Error: ${response.statusCode}');
}
} catch (e) {
print('An error occurred: $e');
}
}
Using Async/Await
• Network calls are asynchronous, use async and await to
wait for the responses. This prevents the UI from
blocking while waiting for the API response.

@override ElevatedButton(
void initState() { onPressed: sendData,
super.initState(); child: Text('Send Data'),
fetchData(); )
}
Handling Errors
• Wrap API calls in a try-catch block to handle any errors
that might occur during network communication, such
as network failures or invalid URLs.
Displaying Data in @override
the UI
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
Widget build(BuildContext context) {
} return Scaffold(
class _MyWidgetState extends State<MyWidget> { appBar: AppBar(title: Text('Posts')),
List<dynamic> posts = []; body: posts.isEmpty
@override ? Center(child: CircularProgressIndicator())
void initState() {
super.initState(); : ListView.builder(
fetchData(); itemCount: posts.length,
}
itemBuilder: (context, index) {
Future<void> fetchData() async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
final post = posts[index];
return ListTile(
try {
final response = await http.get(url); title: Text(post['title']),
if (response.statusCode == 200) {
subtitle: Text(post['body']),
setState(() { );
posts = jsonDecode(response.body);
}); },
} else {
print('Error: ${response.statusCode}');
),
} );
} catch (e) {
print('An error occurred: $e'); }
}
} }
USING FUTURE BUILDER
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

Future<List<dynamic>> fetchPosts() async {


final url =
Uri.parse('https://jsonplaceholder.typicode.com/posts');

try {
final response = await http.get(url);

if (response.statusCode == 200) {
// Parse the JSON response into a list
return jsonDecode(response.body);
} else {
throw Exception('Failed to load posts');
}
} catch (e) {
throw Exception('Error: $e');
}
}
class PostsScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Posts'),
),
body: FutureBuilder<List<dynamic>>(
future: fetchPosts(),
builder: (context, snapshot) {
// Display a loading indicator while the data is loading
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}

// Handle errors
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
if (snapshot.hasData) {
final posts = snapshot.data!;
return ListView.builder(
itemCount: posts.length,
itemBuilder: (context, index) {
final post = posts[index];
return ListTile(
title: Text(post['title']),
subtitle: Text(post['body']),
);},);}
// Default case when there's no data yet
return Center(child: Text('No data available'));
}, ), ); }
}

You might also like