美文网首页
flutter05: 请求接口函数封装

flutter05: 请求接口函数封装

作者: 蜗牛的学习方法 | 来源:发表于2019-06-17 14:38 被阅读0次

    下载插件 dio: ^2.1.7

    import 'package:dio/dio.dart';
    import 'dart:async';
    import 'dart:io';
    import './service.dart';
    
    //POST 请求
    Future post(type,data) async{
      try{
        Response response;
        Dio dio=new Dio();
        dio.interceptors.add(InterceptorsWrapper(
          onRequest:(Options options) async{
            options.headers["token"] = token;
            return options; //continue
          }
        ));
        response=await dio.post(service[type],data:data);
        if(response.statusCode==200){
          return response.data;
        }else{
          throw Exception('后端接口出现异常');
        }
      }catch(e){
        return print('error:$e');
      }
    }
    
    //GET 请求
    Future get(type,data) async{
      try{
        Response response;
        Dio dio=new Dio();
        dio.interceptors.add(InterceptorsWrapper(
          onRequest:(Options options) async{
            options.headers["token"] = token;
            return options; //continue
          }
        ));
        response=await dio.post(service[type],queryParameters: data);
        if(response.statusCode==200){
          return response.data;
        }else{
          throw Exception('后端接口出现异常');
        }
      }catch(e){
        return print('error:$e');
      }
    }
    

    使用:

    get('systemConfig', {}).then((res){
        print('@@@$res');
     });
    

    相关文章

      网友评论

          本文标题:flutter05: 请求接口函数封装

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