Technology Encyclopedia Home >How to make network requests in Flutter?

How to make network requests in Flutter?

To make network requests in Flutter, you can use the http package, which is a popular and easy-to-use library for making HTTP requests. Here's a step-by-step guide:

Step 1: Add the http Package to Your Project

First, you need to add the http package to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3

Then, run flutter pub get to fetch the package.

Step 2: Import the http Package in Your Dart File

Import the http package in the Dart file where you want to make the network request:

import 'package:http/http.dart' as http;

Step 3: Make a Network Request

You can make a GET request as follows:

Future<void> fetchData() async {
  final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response, then parse the JSON.
    print('Response data: ${response.body}');
  } else {
    // If the server did not return a 200 OK response, then throw an exception.
    throw Exception('Failed to load posts');
  }
}

Step 4: Handle the Response

You can parse the JSON response using the dart:convert library:

import 'dart:convert';

Future<void> fetchData() async {
  final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));

  if (response.statusCode == 200) {
    List<dynamic> jsonResponse = json.decode(response.body);
    print('Parsed JSON: $jsonResponse');
  } else {
    throw Exception('Failed to load posts');
  }
}

Example: Making a POST Request

Here's an example of making a POST request:

Future<void> postData() async {
  final response = await http.post(
    Uri.parse('https://jsonplaceholder.typicode.com/posts'),
    headers: {'Content-Type': 'application/json'},
    body: jsonEncode({
      'title': 'foo',
      'body': 'bar',
      'userId': 1,
    }),
  );

  if (response.statusCode == 201) {
    print('Post created: ${response.body}');
  } else {
    throw Exception('Failed to create post');
  }
}

Recommendation for Cloud Services

If you are looking to deploy your Flutter application and handle backend services, consider using Tencent Cloud. Tencent Cloud offers a variety of services that can support your application's backend needs, such as Cloud Functions for serverless computing, API Gateway for managing APIs, and Cloud Storage for storing static assets.

By leveraging these services, you can ensure that your application has a robust backend infrastructure while focusing on the frontend development with Flutter.