flutter05: 请求接口函数封装

下载插件 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: 请求接口函数封装)