Flutter简单的dio封装以及从网络获取数据

2022年9月15日 1003点热度 0人点赞 0条评论

效果图:
Flutter简单的dio封装以及从网络获取数据插图

1、简单的dio封装类:MyHttpRequest

<code>import &#039;package:dio/dio.dart&#039;;
import &#039;package:flutter/material.dart&#039;;
import &#039;dio_response.dart&#039;;

class MyHttpRequest{
   static const int _connectTimeout = 6*1000;
   static const int _receiveTimeout = 6*1000;

   Dio? _dio;

   //声明本类实例
   static MyHttpRequest? _instance;

   factory MyHttpRequest()=&gt;_instance ?? MyHttpRequest._internal();

       //获取本类实例
   static MyHttpRequest? getInstance(){
     _instance ??= MyHttpRequest._internal();
     return _instance;
   }

   MyHttpRequest._internal(){
     _instance = this;
     _instance?._init();
   }

   _init(){
     BaseOptions options = BaseOptions(
         baseUrl: &quot;http://192.168.31.153:8989&quot;,
         connectTimeout: _connectTimeout,
         receiveTimeout: _receiveTimeout
     );
     _dio = Dio(options);
   }

   //async...await...返回的是一个Future
   Future&lt;DioResponse&gt; send(String pathUrl,{Map&lt;String,dynamic&gt;? 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(&quot;send:获取网络数据成功。。。&quot;);
       result = DioResponse.fromJson(response!.data);
       debugPrint(result.toString());
     }else{
       debugPrint(&quot;send:获取网络数据失败。。。${response?.statusMessage}&quot;);
     }

     return result!;
   }
}

enum MyHttpMethod{
  get,post,delete
}</code>

2、界面使用封装类发起网络请求:

<code>
import &#039;package:dio/dio.dart&#039;;
import &#039;package:flutter/material.dart&#039;;
import &#039;package:hot_shop/Utils/Entity/user_entity.dart&#039;;
import &#039;package:hot_shop/Utils/Network/my_http_request.dart&#039;;
import &#039;Utils/Network/dio_response.dart&#039;;

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&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();
}

class _MyHomePageState extends State&lt;MyHomePage&gt; {

  UserEntity? userEntity;

  _changeData(UserEntity user){
    setState(() {
      userEntity = user;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(&quot;Dio网络请求案列&quot;),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: (){
                //数据改变
                _getData().then((value) =&gt; {
                  _changeData(value)
                });
              },
              child: const Text(&quot;点击获取数据&quot;,style: TextStyle(fontWeight: FontWeight.bold),),
            ),
            const SizedBox(height: 16),
            Container(
                alignment: Alignment.center,
                width: 180,
                //height: 10,
                color: Colors.greenAccent,
                child: Text(&quot;获取的数据是:${userEntity?.name ?? &quot;暂无数据&quot;}&quot;)
            )
          ],
        ),
      ),
    );
  }

  Future&lt;UserEntity&gt; _getData() async{
    UserEntity user;
    CancelToken cancelToken = CancelToken();
    DioResponse? response =await MyHttpRequest.getInstance()?.send(&quot;/user/login&quot;,method: MyHttpMethod.get);
    user = UserEntity.fromJson(response?.data);
    debugPrint(user.name);
    //debugPrint(user[&#039;data&#039;]);
    return user;
  }
}
</code>

小小调酒师

此刻打盹,你将做梦; 此刻学习,你将圆梦。 个人邮箱:shellways@foxmail.com

文章评论