美文网首页熊爸的学习时间
轻松flutter之 网络请求DIO

轻松flutter之 网络请求DIO

作者: 熊爸天下_56c7 | 来源:发表于2020-05-06 16:48 被阅读0次

    这是比http库更强大的库哦

    https://pub.dev/packages/dio
    https://github.com/flutterchina/dio/blob/master/README-ZH.md

    将http文章中的例子改造成dio

    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(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: MyHomePage2(),
        );
      }
    }
    
    class MyHomePage2 extends StatefulWidget {
      @override
      _MyHomePage2State createState() => _MyHomePage2State();
    }
    
    class _MyHomePage2State extends State<MyHomePage2> {
      String _getMsg = '';
      String _postMsg = '';
      String _getRealMsg = '';
    
      _getData() async {
        try {
          Response response = await Dio()
              .get("http://rap2.taobao.org:38080/app/mock/253219/apiget");
          print(response);
          setState(() {
            _getMsg = response.data["msg"];
          });
        } catch (e) {
          print(e);
        }
      }
    
      _getRealData() async {
        try {
          Response response =
              await Dio().get("http://a.itying.com/api/productlist");
          print(response);
          setState(() {
            _getRealMsg = response.data.toString();
          });
        } catch (e) {
          print(e);
        }
      }
    
      _postData() async {
        try {
          Response response = await Dio().post(
              "http://rap2.taobao.org:38080/app/mock/253219/apipost",
              data: {"name": "abc", "color": "blue"});
          print(response);
          setState(() {
            _postMsg = response.data['name'];
          });
        } catch (e) {
          print(e);
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text("DIO网络请求"),
          ),
          body: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    RaisedButton(child: Text('get'), onPressed: _getData),
                    SizedBox(
                      width: 20,
                    ),
                    Text(_getMsg)
                  ],
                ),
                Row(
                  children: <Widget>[
                    RaisedButton(child: Text('post'), onPressed: _postData),
                    SizedBox(
                      width: 20,
                    ),
                    Text(_postMsg)
                  ],
                ),
                RaisedButton(
                    child: Text("get请求个真实数据http://a.itying.com/api/productlist"),
                    onPressed: _getRealData),
                SizedBox(
                  width: 20,
                ),
                Text(_getRealMsg)
              ],
            ),
          ),
        );
      }
    }
    

    除了这些简单用法,dio还可以

    • 下载文件 response = await dio.download("https://www.google.com/", "./xx.html");
    • 流方式接受响应数据
    Response<ResponseBody> rs = await Dio().get<ResponseBody>(url,
      options: Options(responseType: ResponseType.stream), //设置接收类型为stream
    );
    print(rs.data.stream); //响应流
    
    • 自定义请求头
    • 请求拦截
    dio.interceptors.add(InterceptorsWrapper(
        onRequest:(RequestOptions options) async {
         // 在请求被发送之前做一些事情
         return options; //continue
         // 如果你想完成请求并返回一些自定义数据,可以返回一个`Response`对象或返回`dio.resolve(data)`。
         // 这样请求将会被终止,上层then会被调用,then中返回的数据将是你的自定义数据data.
         //
         // 如果你想终止请求并触发一个错误,你可以返回一个`DioError`对象,或返回`dio.reject(errMsg)`,
         // 这样请求将被中止并触发异常,上层catchError会被调用。
        },
        onResponse:(Response response) async {
         // 在返回响应数据之前做一些预处理
         return response; // continue
        },
        onError: (DioError e) async {
          // 当请求失败时做一些预处理
         return e;//continue
        }
    ));
    
    • 以二进制数组的方式接收响应数据
    • 发送 FormData
    • 通过FormData上传多个文件
    • 监听发送(上传)数据进度
    • 以流的形式提交二进制数据

    详见参考文档.

    官方实例:

    https://github.com/flutterchina/dio/blob/master/example/options.dart

    import 'dart:io';
    import 'package:dio/dio.dart';
    
    main() async {
      var dio = Dio(BaseOptions(
        baseUrl: "http://httpbin.org/",
        connectTimeout: 5000,
        receiveTimeout: 100000,
        // 5s
        headers: {
          HttpHeaders.userAgentHeader: "dio",
          "api": "1.0.0",
        },
        contentType: Headers.jsonContentType,
        // Transform the response data to a String encoded with UTF8.
        // The default value is [ResponseType.JSON].
        responseType: ResponseType.plain,
      ));
    
      Response response;
    
      response = await dio.get("/get");
      print(response.data);
    
      Response<Map> responseMap = await dio.get(
        "/get",
        // Transform response data to Json Map
        options: Options(responseType: ResponseType.json),
      );
      print(responseMap.data);
      response = await dio.post(
        "/post",
        data: {
          "id": 8,
          "info": {"name": "wendux", "age": 25}
        },
        // Send data with "application/x-www-form-urlencoded" format
        options: Options(
          contentType: Headers.formUrlEncodedContentType,
        ),
      );
      print(response.data);
    
      response = await dio.request(
        "/",
        options: RequestOptions(baseUrl: "https://baidu.com"),
      );
      print(response.data);
    }
    

    相关文章

      网友评论

        本文标题:轻松flutter之 网络请求DIO

        本文链接:https://www.haomeiwen.com/subject/zquwghtx.html