#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:
1dependencies:2http: ^0.13.3
Fetching Data from an API
1import 'package:flutter/material.dart';2import 'package:http/http.dart' as http;3import 'dart:convert';45void main() {6runApp(FetchDataApp());7}89// Fetching data from the internet using the http package10class FetchDataApp extends StatefulWidget {11@override12_FetchDataAppState createState() => _FetchDataAppState();13}1415class _FetchDataAppState extends State<FetchDataApp> {16String _data = 'Loading...';1718// Method to fetch data from an API19void fetchData() async {20final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));2122if (response.statusCode == 200) {23setState(() {24_data = jsonDecode(response.body)['title']; // Decode the JSON response25});26} else {27setState(() {28_data = 'Failed to load data';29});30}31}3233@override34void initState() {35super.initState();36fetchData(); // Fetch data when the app initializes37}3839@override40Widget build(BuildContext context) {41return Scaffold(42appBar: AppBar(title: Text('Fetch Data Example')),43body: Center(44child: Text(_data), // Display the fetched data45),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