0
0
Fluttermobile~5 mins

GET and POST requests in Flutter

Choose your learning style9 modes available
Introduction

GET and POST requests let your app talk to the internet. GET asks for data, POST sends data.

When you want to load a list of items from a website or server.
When you need to send a form or user input to a server.
When your app needs to update information on a remote database.
When fetching user profile details from an online service.
When submitting feedback or comments from your app.
Syntax
Flutter
import 'package:http/http.dart' as http;

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

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

Use http.get to fetch data without changing anything on the server.

Use http.post to send data to the server, like submitting a form.

Examples
This GET request fetches a single post from a test API.
Flutter
var response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
This POST request sends a new post with title and body to the server.
Flutter
var response = await http.post(
  Uri.parse('https://jsonplaceholder.typicode.com/posts'),
  body: {'title': 'Hello', 'body': 'World'},
);
Sample App

This Flutter app has two buttons. One button fetches data from the internet using a GET request and shows the title of a post. The other button sends data using a POST request and shows a success or failure message.

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

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

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

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

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

  Future<void> sendData() async {
    final response = await http.post(
      Uri.parse('https://jsonplaceholder.typicode.com/posts'),
      body: json.encode({'title': 'Flutter', 'body': 'POST request example'}),
      headers: {'Content-Type': 'application/json; charset=UTF-8'},
    );
    if (response.statusCode == 201) {
      setState(() {
        _data = 'Data sent successfully!';
      });
    } else {
      setState(() {
        _data = 'Failed to send data';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('GET and POST Requests')),
        body: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(_data, textAlign: TextAlign.center),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: fetchData,
                child: Text('GET Data'),
              ),
              SizedBox(height: 10),
              ElevatedButton(
                onPressed: sendData,
                child: Text('POST Data'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Always check the response status code to know if the request worked.

Use Uri.parse to convert the URL string to a Uri object.

Network calls are asynchronous, so use await inside async functions.

Summary

GET requests fetch data from a server without changing it.

POST requests send data to a server to create or update something.

Use the http package in Flutter to make these requests easily.