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);
  }
}
相关推荐
因_崔斯汀1 小时前
用 AI 生成 Three.js 沉浸式网站,代码与 Skill 均已开源
前端·人工智能
葡萄城技术团队1 小时前
一键触发工作表中所有异步函数:用依赖单元格刷新 SpreadJS 公式
前端
Bigger1 小时前
谁动了我的 URL?——记一次微前端"灵异 Bug"的排查实录
前端·ai编程·vue-router
JavaGuide2 小时前
轻量开源版 IDEA 来了!
前端·后端
张洪权2 小时前
nest.js websocket 群聊----私聊功能
前端·nestjs
流光D2 小时前
AI Era: Building Web Sites and Configuring Nginx Reverse Proxy Process
前端·人工智能·nginx
sakidd2 小时前
VS Code 的 AI Chat 现在已经这么能干了?
前端
计算机魔术师2 小时前
英伟达砸130亿美元买下一个平台,黄仁勋到底在怕什么?
前端
leoZ2312 小时前
第 2 篇:搭建地基——Vue3 + Vite + Tailwind v4 + shadcn-vue
前端·javascript·vue.js·人工智能·目标检测·数据挖掘·语音识别
coderCN2 小时前
Nodejs path OS process child_process FS crypto zlib ffmpeg Markdown 转 html
前端