0
0
Fluttermobile~10 mins

Dio package for advanced HTTP in Flutter

Choose your learning style9 modes available
Introduction

Dio helps your app talk to the internet easily and powerfully. It manages requests and responses with extra features.

You want to fetch data from a web server with headers and parameters.
You need to handle errors like timeouts or bad responses gracefully.
You want to upload or download files with progress updates.
You want to add interceptors to modify requests or responses automatically.
You need to cancel requests if the user leaves a screen.
Syntax
Flutter
final dio = Dio();

// Making a GET request
final response = await dio.get('https://example.com/api/data',
  queryParameters: {'key': 'value'},
  options: Options(headers: {'Authorization': 'Bearer token'}),
);

// Handling response
print(response.data);

Use Dio() to create a client for HTTP calls.

Use get, post, put, etc. methods for requests.

Examples
Simple GET request to fetch posts data.
Flutter
final dio = Dio();
final response = await dio.get('https://jsonplaceholder.typicode.com/posts');
print(response.data);
POST request sending login data in the body.
Flutter
final dio = Dio();
final response = await dio.post('https://example.com/login', data: {'username': 'user', 'password': 'pass'});
print(response.data);
Adding interceptors to log requests, responses, and errors.
Flutter
final dio = Dio();
dio.interceptors.add(InterceptorsWrapper(
  onRequest: (options, handler) {
    print('Request to: ' + options.uri.toString());
    return handler.next(options);
  },
  onResponse: (response, handler) {
    print('Response status: ' + response.statusCode.toString());
    return handler.next(response);
  },
  onError: (DioError e, handler) {
    print('Error: ' + e.message);
    return handler.next(e);
  },
));
Sample App

This app uses Dio to fetch a list of posts from a public API. It shows a loading spinner while waiting, then displays the posts in a scrollable list. If loading fails, it shows an error message.

Flutter
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Dio HTTP Example')),
        body: Center(child: PostsList()),
      ),
    );
  }
}

class PostsList extends StatefulWidget {
  @override
  _PostsListState createState() => _PostsListState();
}

class _PostsListState extends State<PostsList> {
  final Dio dio = Dio();
  List<dynamic> posts = [];
  bool loading = true;
  String error = '';

  @override
  void initState() {
    super.initState();
    fetchPosts();
  }

  Future<void> fetchPosts() async {
    try {
      final response = await dio.get('https://jsonplaceholder.typicode.com/posts');
      setState(() {
        posts = response.data;
        loading = false;
      });
    } catch (e) {
      setState(() {
        error = 'Failed to load posts';
        loading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (loading) {
      return CircularProgressIndicator();
    }
    if (error.isNotEmpty) {
      return Text(error);
    }
    return ListView.builder(
      itemCount: posts.length,
      itemBuilder: (context, index) {
        final post = posts[index];
        return ListTile(
          title: Text(post['title']),
          subtitle: Text(post['body']),
        );
      },
    );
  }
}
OutputSuccess
Important Notes

Dio supports request cancellation using CancelToken.

You can add interceptors to modify requests or handle errors globally.

Use Options to customize headers, timeouts, and response types.

Summary

Dio is a powerful HTTP client for Flutter with many features.

It simplifies making requests, handling errors, and customizing calls.

Use interceptors and options to control request and response behavior.