0
0
Fluttermobile~5 mins

http package in Flutter

Choose your learning style9 modes available
Introduction

The http package helps your app talk to the internet. It lets you get or send data from websites or servers easily.

When you want to get weather data from an online service.
When your app needs to send user info to a server.
When you want to load news articles from a website.
When you need to download images or files from the internet.
When your app communicates with a backend to save or fetch data.
Syntax
Flutter
import 'package:http/http.dart' as http;

// To make a GET request
var response = await http.get(Uri.parse('https://example.com'));

// To make a POST request
var response = await http.post(Uri.parse('https://example.com'), body: {'key': 'value'});

Always use Uri.parse() to convert the URL string.

Use await because these calls take time and run asynchronously.

Examples
This fetches a single post from a test API using GET.
Flutter
var response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
This sends login data to a server using POST.
Flutter
var response = await http.post(Uri.parse('https://example.com/login'), body: {'username': 'user', 'password': 'pass'});
Check if the request was successful by looking at the status code.
Flutter
print('Status code: ' + response.statusCode.toString());
Sample App

This app shows a button. When pressed, it fetches a post from the internet and shows the text on screen.

Flutter
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String data = 'Press the button to fetch data';

  Future<void> fetchData() async {
    final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
    if (response.statusCode == 200) {
      setState(() {
        data = response.body;
      });
    } else {
      setState(() {
        data = 'Failed to load data';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('HTTP Package Example')),
        body: Padding(
          padding: EdgeInsets.all(16),
          child: Column(
            children: [
              Expanded(child: SingleChildScrollView(child: Text(data))),
              ElevatedButton(
                onPressed: fetchData,
                child: Text('Fetch Data'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Use async and await to handle network calls smoothly.

Check response.statusCode to know if the request worked (200 means success).

Always handle errors like no internet or bad responses to avoid app crashes.

Summary

The http package lets your app get or send data over the internet.

Use http.get() for fetching data and http.post() for sending data.

Remember to use Uri.parse() and check the response status code.