Flutter (十七) 网络请求

网络请求

安装dio,在项目目录文件中执行flutter pub add dio

javascript 复制代码
import 'package:dio/dio.dart';

void main(List<String> args) {
  Dio().get("https://geek.itheima.net/v1_0/channels").then((data){
    print(data);
  });
}

项目中使用dio

vbnet 复制代码
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

void main(List<String> args) {
  // Dio().get("https://geek.itheima.net/v1_0/channels").then((data) {
  //   print(data);
  // });
  runApp(MaterialApp(home: HomePage()));
}

class HomePage extends StatefulWidget {
  HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List _channels = [];
  @override
  void initState() {
    super.initState();
    print("initstate");
    getChannle();
  }

  void getChannle() async {
    DioUtils net = DioUtils();
    Response<dynamic> res = await net.get("channels");
    /*
    {
      "data": {
        "channels": [
          { "id": 0, "name": "推荐" },
          { "id": 1, "name": "html" },
          { "id": 2, "name": "开发者资讯" },
          { "id": 4, "name": "c++" },
          { "id": 6, "name": "css" },
          { "id": 7, "name": "数据库" },
          { "id": 8, "name": "区块链" },
          { "id": 9, "name": "go" },
          { "id": 10, "name": "产品" },
          { "id": 11, "name": "后端" },
          { "id": 12, "name": "linux" },
          { "id": 13, "name": "人工智能" },
          { "id": 14, "name": "php" },
          { "id": 15, "name": "javascript" },
          { "id": 16, "name": "架构" },
          { "id": 17, "name": "前端" },
          { "id": 18, "name": "python" },
          { "id": 19, "name": "java" },
          { "id": 20, "name": "算法" },
          { "id": 21, "name": "面试" },
          { "id": 22, "name": "科技动态" },
          { "id": 23, "name": "js" },
          { "id": 24, "name": "设计" },
          { "id": 25, "name": "数码产品" },
          { "id": 26, "name": "软件测试" }
        ]
      },
      "message": "OK"
    }
  */
    print(res.data);
    Map<String, dynamic> data = res.data as Map<String, dynamic>;
    List channels = data["data"]["channels"] as List;
    // List mapList =
    //     channels.cast<Map<String, dynamic>>() as List<Map<String, dynamic>>;
    List mapList = channels.cast<Map<String, dynamic>>();
    setState(() {
      _channels = mapList;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Dio学习")),
      body: GridView.extent(
        maxCrossAxisExtent: 100,
        children: List.generate(_channels.length, (index) {
          return Text(_channels[index]["name"]);
        }),
      ),
    );
    // return Container(child: GridView.builder(gridDelegate: gridDelegate, itemBuilder: itemBuilder));
  }
}

class DioUtils {
  final Dio _dio = Dio();
  DioUtils() {
    // _dio.options.baseUrl = "https://geek.itheima.net/v1_0/channels";
    // _dio.options.connectTimeout = Duration(seconds: 10);
    // _dio.options.sendTimeout = Duration(seconds: 10);
    // _dio.options.receiveTimeout = Duration(seconds: 10);

    _dio.options
      ..baseUrl = "https://geek.itheima.net/v1_0/"
      ..connectTimeout = Duration(seconds: 10)
      // ..sendTimeout = Duration(seconds: 10)
      ..receiveTimeout = Duration(seconds: 10);

    _addIntercepter();
  }

  void _addIntercepter() {
    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (context, handle) {
          handle.next(context);

          // handle.reject(Error);
        },
        onResponse: (context, handle) {
          if (context.statusCode! == 200) {
            handle.next(context);
            return;
          }
          handle.reject(DioException(requestOptions: context.requestOptions));
        },
        onError: (context, handle) {
          handle.reject(context);
        },
      ),
    );
  }

  Future<Response<dynamic>> get(String url, {Map<String, dynamic>? params}) {
    return _dio.get(url, queryParameters: params);
  }
}
相关推荐
子兮曰2 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰2 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万2 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝2 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋2 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁2 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
汉堡大王95272 天前
Jev:不是聊天机器人, 而是一个智能 if 语句
前端·人工智能·后端
梦想很大很大2 天前
从运行事实到回归证据:Workrun 的 Telemetry 与 Evaluation 实践
前端·人工智能·后端
计算机魔术师2 天前
Meta Muse agent 接入 Shopify 的 Shop Pay 实现代理式购物
前端
沙蒿同学2 天前
我用 Go 搭了一条 AI Agent 流水线:从 1 张商品图到一整套淘宝详情页
前端·javascript·后端