Flutter University
  • πŸ‘‹Welcome to Flutter University
  • Learn Flutter
    • πŸš—Basics
      • 🧺Dart Basics
      • πŸš›Setup & Installation
      • 🐣Hello Flutter
      • πŸŒ‰Widgets
      • ⛸️Basic State Management
      • πŸ‡ΎπŸ‡ΉBasic Layout and Styling
      • 🐝Basic Interactivity
      • πŸ›£οΈNavigation
      • πŸͺ„Working with Assets
    • πŸš…Intermediate
      • 🎯Deeper into Dart
      • ⭐More on State Management
      • πŸ“ƒForm Handling
      • πŸ—ΌNetworking
      • πŸŽ‡Persistence
      • πŸ§™β€β™‚οΈAnimations
      • πŸ§ͺTesting
      • πŸ“¦Package Management
    • ✈️Professional
      • πŸŽ“Advanced Animations
      • 🎨Custom Painters
      • 🐼Continuous Integration/Continuous Deployment (CI/CD)
      • 🎭Performance Profiling
      • πŸ”¬Native Integrations
      • 🌍Accessibility and Localization
      • 🀘Understanding Design Patterns
      • πŸ“šFlutter Architecture
        • The Layer Model
        • Reactive User Interfaces
        • Flutter Widgets
        • The Rendering Process
        • Platform Embedders Overview
        • Integrating with Other Code
        • Support for the Web
  • Tutorials
    • 🌈UI
      • 🏚️Clubhouse Clone
      • πŸ”‰Netflix Clone
    • βš”οΈFull Stack
    • ⛓️Blockchain
    • πŸ€–AI/ML
  • Miscellaneous
    • πŸ–₯️100 Days of Flutter
    • 🎨Join Community
Powered by GitBook
On this page
  • 1. Adding the http Package πŸ“¦
  • 2. Sending a GET Request πŸ“€
  • 3. Sending a POST Request πŸ“₯
  • 4. Error Handling πŸ›‘
  • Complete Example Code πŸ“œ
  • Assignments πŸ“

Was this helpful?

  1. Learn Flutter
  2. Intermediate

Networking

In Flutter, the http package is commonly used for sending HTTP requests to a server. Let’s explore how you can perform GET and POST requests.

1. Adding the http Package πŸ“¦

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

dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0

Run flutter pub get to install the new dependency.

2. Sending a GET Request πŸ“€

Here’s how you can send a GET request to fetch data from a server:

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

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

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

3. Sending a POST Request πŸ“₯

Here’s how you can send a POST request to create new data on a server:

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

Future<void> createPost() async {
  final response = await http.post(
    Uri.parse('https://jsonplaceholder.typicode.com/posts'),
    body: {
      'title': 'foo',
      'body': 'bar',
      'userId': '1',
    },
  );

  if (response.statusCode == 201) {
    // If the server returns a CREATED response, parse the JSON
    print('Created post: ${response.body}');
  } else {
    // If the server did not return a 201 CREATED response, throw an exception.
    throw Exception('Failed to create post');
  }
}

4. Error Handling πŸ›‘

It's important to handle any errors that occur when sending requests:

try {
  await fetchPost();
} catch (error) {
  print('Failed to load post: $error');
}

Complete Example Code πŸ“œ

Let's put everything together in a complete Flutter app:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: NetworkingExample(),
    );
  }
}

class NetworkingExample extends StatefulWidget {
  @override
  State<NetworkingExample> createState() => _NetworkingExampleState();
}

class _NetworkingExampleState extends State<NetworkingExample> {
  String _data = 'Press button to fetch data';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Networking Example'),
      ),
      body: Center(
        child: Text(_data),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: fetchData,
        child: Icon(Icons.cloud_download),
      ),
    );
  }
}

In this complete example:

  • We first add the http dependency in pubspec.yaml.

  • We define a NetworkingExample stateful widget.

  • In the _NetworkingExampleState class, we define a fetchData method that sends a GET request to fetch data.

  • We use a FloatingActionButton to trigger the fetchData method.

  • We display the fetched data or any error messages to the user.


Assignments πŸ“

Here are some exercises to reinforce your understanding:

Last updated 1 year ago

Was this helpful?

πŸš…
πŸ—Ό