1、简单的dio封装类:MyHttpRequest
<code>import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'dio_response.dart'; class MyHttpRequest{ static const int _connectTimeout = 6*1000; static const int _receiveTimeout = 6*1000; Dio? _dio; //声明本类实例 static MyHttpRequest? _instance; factory MyHttpRequest()=>_instance ?? MyHttpRequest._internal(); //获取本类实例 static MyHttpRequest? getInstance(){ _instance ??= MyHttpRequest._internal(); return _instance; } MyHttpRequest._internal(){ _instance = this; _instance?._init(); } _init(){ BaseOptions options = BaseOptions( baseUrl: "http://192.168.31.153:8989", connectTimeout: _connectTimeout, receiveTimeout: _receiveTimeout ); _dio = Dio(options); } //async...await...返回的是一个Future Future<DioResponse> send(String pathUrl,{Map<String,dynamic>? params,required MyHttpMethod method,Options? options,CancelToken? cancelToken}) async{ Response? response; DioResponse? result; //简化get和post请求,通过传参数方式决定请求方法 switch(method){ case MyHttpMethod.get: response =await _dio?.get(pathUrl,queryParameters: params,options: options,cancelToken:cancelToken);//options: Options(responseType: ResponseType.plain break; case MyHttpMethod.post: response =await _dio?.post(pathUrl,queryParameters: params,options: options,cancelToken:cancelToken); break; } //处理结果 if(response?.statusCode==200){ debugPrint("send:获取网络数据成功。。。"); result = DioResponse.fromJson(response!.data); debugPrint(result.toString()); }else{ debugPrint("send:获取网络数据失败。。。${response?.statusMessage}"); } return result!; } } enum MyHttpMethod{ get,post,delete }</code>
2、界面使用封装类发起网络请求:
<code> import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:hot_shop/Utils/Entity/user_entity.dart'; import 'package:hot_shop/Utils/Network/my_http_request.dart'; import 'Utils/Network/dio_response.dart'; main(){ runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { UserEntity? userEntity; _changeData(UserEntity user){ setState(() { userEntity = user; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Dio网络请求案列"), centerTitle: true, ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: (){ //数据改变 _getData().then((value) => { _changeData(value) }); }, child: const Text("点击获取数据",style: TextStyle(fontWeight: FontWeight.bold),), ), const SizedBox(height: 16), Container( alignment: Alignment.center, width: 180, //height: 10, color: Colors.greenAccent, child: Text("获取的数据是:${userEntity?.name ?? "暂无数据"}") ) ], ), ), ); } Future<UserEntity> _getData() async{ UserEntity user; CancelToken cancelToken = CancelToken(); DioResponse? response =await MyHttpRequest.getInstance()?.send("/user/login",method: MyHttpMethod.get); user = UserEntity.fromJson(response?.data); debugPrint(user.name); //debugPrint(user['data']); return user; } } </code>
文章评论