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);
  }
}
相关推荐
薛定谔的猫-菜鸟程序员13 分钟前
Electron开发超详细教程(从入门到放弃)
前端·javascript·electron
最强小杰34 分钟前
DeepSeek V4 Flash + Codex CLI 接入教程:原生 Responses API 适配,从配置到跑通收藏这篇就够了(2026)
java·前端·python·ai
静水leo1 小时前
使用 Whistle 拦截接口并模拟后端响应
前端
掘金者阿豪1 小时前
SQL Server数据迁移完成后,凌晨的数据库告警该怎么查?
前端·后端
JudithHuang1 小时前
React 嵌套路由与布局
前端·react.js·arcgis·react·react router
htzyl2061 小时前
前端阶梯——第四十三章、实战二:待办清单To-Do
前端·javascript·html
摹客2 小时前
【3D设计】界面设计中的3D元素:应用场景+5款工具横评(含Three.js)
前端
Hilaku2 小时前
CORS 到底在保护谁?90% 的前端理解错了跨域的本质
前端·javascript·程序员
wno7043 小时前
node.js中使用jquery
前端·node.js·jquery