Flutter and Dio network interaction

preface

The most popular library for Flutter is the Dio library. How to use this library? How to implement a general package? See below:

Install dio library (dio: ^4.0.4)Github.com/flutterchin…

flutter pub add dio

Ii. Basic use of DIO
import 'package:dio/dio.dart';

// NetEase cloud API is used here, thanks for open source, thanks for sharing! Official address Portal:
// https://binaryify.github.io/NeteaseCloudMusicApi/#/

void send() async {
   final query = {'id': 186016.'limit': 1};
   try {
        // instantiate Dio, passing in parameters to make a GET request
      final result = await Dio().get(
          'http://123.207.32.32:9001/comment/music',
          queryParameters: query,
      );
        // Print the result
      print(result);
   } catch (e) {
        // Print exception
      print(e); }}Copy the code

The step to using DIO is to instantiate a dio and use that instance to make some requests (maybe passing in some parameters), so the question is, should every page generate an instance of dio? Or there is a way to better manage DIO. Yes, there is.

Three: DIO basic package

Generally speaking, it is mainly to make a general encapsulation of the configuration information of the request and the network interceptor. The idea adopted here is to use a class to save the instance of DIO, and then the instance can be used globally for network requests

  • Write network configuration classes

    class NetworkConfig {
      static const String baseUrl = 'http://123.207.32.32:9001/';
    
      static const int sendTimeout = 8000;
    
      static const int connectTimeout = 8000;
    
      static const int receiveTimeout = 8000;
    
    }
    Copy the code
  • Write interface tool classes (save commonly used interfaces for easy management)

    class EndPoint {
      static const String comment = 'comment/music';
    }
    Copy the code
  • Write dio interceptors

    // Interceptors can do a number of things, as shown in the official documentation
    // If we need to add a token in the request, we can do it in onRequest
    class NetworkIntercept extends Interceptor {
      @override
      void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
        // The AppCache class is described in my last article
        // Add tokens from the cache. This is just an example. There are other ways to add tokens
        final String? token = AppCache.token;
        if(token ! =null) {
          options.headers['token'] = token;
        }
        super.onRequest(options, handler);
      }
    
      @override
      void onResponse(Response response, ResponseInterceptorHandler handler) {
          super.onResponse(response, handler);
      }
    
      @override
      void onError(DioError err, ErrorInterceptorHandler handler) {
        super.onError(err, handler); }}Copy the code
  • Write a singleton class that holds Dio,

    import 'package:dio/dio.dart';
    import 'package:flutter_network/cache/cache.dart';
    import 'package:flutter_network/network/network_config.dart';
    
    class Network {
      final Dio dio;
    
      Network._({required this.dio});
    
      factory Network._create(Dio dio) => Network._(dio: dio);
    
      static Network? _client;
    
      static void init() {
        if (_client == null) {
          // Create configuration information
          final BaseOptions options = BaseOptions(
            baseUrl: NetworkConfig.baseUrl,
            sendTimeout: NetworkConfig.sendTimeout,
            connectTimeout: NetworkConfig.connectTimeout,
            receiveTimeout: NetworkConfig.receiveTimeout,
          );
    
          // Create the DIO instance and add the configuration information
          final Dio dio = Dio(options);
    
          // Add the interceptor above to dio
          dio.interceptors.add(NetworkIntercept());
    
          // Create a network instance and save it_client = Network._create(dio); }}// Return the processed dio instance externally
      static Dio getinstance => _client! .dio; }Copy the code
  • After encapsulation, we need to initialize the main function as follows:

    import 'package:flutter/material.dart';
    import 'package:flutter_network/cache/cache.dart';
    import 'package:flutter_network/network/network.dart';
    import 'package:flutter_network/view/home_page.dart';
    
    Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
      // Initialize the cache singleton class
      // The AppCache class is described in my last article
      await AppCache.init();
      // Initialize the network singleton class
      Network.init();
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        returnMaterialApp( theme: ThemeData( primarySwatch: Colors.blue, ), home: HomePage(), ); }}Copy the code
  • So once packaged, how do we use it? Simple, on the code:

    import 'package:dio/dio.dart';
    import 'package:flutter/material.dart';
    import 'package:flutter_network/network/end_point.dart';
    import 'package:flutter_network/network/network.dart';
    
    class HomePage extends StatefulWidget {
      const HomePage({Key? key}) : super(key: key);
    
      @override
      _HomePageState createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
      // Reference dio encapsulated in the network singleton class
      final Dio dio = Network.instance;
    
      Future<void> send() async {
        final query = {
          'id': 186016.'limit': 1};try {
          final result = await dio.get(
            EndPoint.comment,
            queryParameters: query,
          );
          print(result);
        } catch (e) {
          print(e); }}@override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Network'),
            centerTitle: true,
          ),
          body: Center(
            child: FloatingActionButton(
              onPressed: send,
              child: Text('click'),),),); }}Copy the code
  • At this point, dio’s simple packaging tutorial is over, if you don’t know anything, please leave a comment in the comments section, or you can share better methods, thanks for watching the iron iron people! 🙂 encapsulation skills are universal, live learning and use is king!

  • Full demo address: github.com/yjf-ll/flut…