Icon
Get In Touch
#flutter

Networking and HTTP Requests

This part covers how to fetch data from APIs using the http package. You will learn to handle asynchronous operations and display dynamic data in your app.

Using the http Package

To interact with a REST API, first, include the http package in your pubspec.yaml file:

1
dependencies:
2
http: ^0.13.3

Fetching Data from an API

1
import 'package:flutter/material.dart';
2
import 'package:http/http.dart' as http;
3
import 'dart:convert';
4
5
void main() {
6
runApp(FetchDataApp());
7
}
8
9
// Fetching data from the internet using the http package
10
class FetchDataApp extends StatefulWidget {
11
@override
12
_FetchDataAppState createState() => _FetchDataAppState();
13
}
14
15
class _FetchDataAppState extends State<FetchDataApp> {
16
String _data = 'Loading...';
17
18
// Method to fetch data from an API
19
void fetchData() async {
20
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
21
22
if (response.statusCode == 200) {
23
setState(() {
24
_data = jsonDecode(response.body)['title']; // Decode the JSON response
25
});
26
} else {
27
setState(() {
28
_data = 'Failed to load data';
29
});
30
}
31
}
32
33
@override
34
void initState() {
35
super.initState();
36
fetchData(); // Fetch data when the app initializes
37
}
38
39
@override
40
Widget build(BuildContext context) {
41
return Scaffold(
42
appBar: AppBar(title: Text('Fetch Data Example')),
43
body: Center(
44
child: Text(_data), // Display the fetched data
45
),
46
);
47
}
48
}

Key Takeaways

- Use the http package to make HTTP requests in Flutter.
- Handle asynchronous operations using async and await.
- Display fetched data dynamically in the UI.

©2024 Codeblockz

Privacy Policy