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);
  }
}
相关推荐
cidy_982 小时前
React 19 + Vite 企业级前端项目:从零搭建到规范交付
前端
用户921080262862 小时前
如何把一张图片做成自定义复杂 UI 图标
前端
用户938515635072 小时前
从 0 拆解一个 Next.js 笔记系统:npx、App Router、RSC 与组件规划全记录
前端·后端·全栈
hello93072 小时前
plop代码生成器
前端
windliang3 小时前
Claude Code 源码分析(十二):错误处理与自动恢复:让 Agent 稳定运行
前端·javascript·面试
fatcoder3 小时前
玩转Docker 06 — 容器网络
前端·后端·docker
打呵欠的猫3 小时前
我用 AI 重写了项目的请求层,从 800 行"面条代码"变成 3 层洋葱模型
前端·ai编程
默_笙3 小时前
🛬 前端路由的"高级玩法":懒加载、404、鉴权路由,一个都不能少(下篇)
前端·javascript
用户921080262863 小时前
1. Cesium 在 Vue 项目中的简单初始化配置
前端