Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flutter 結合 Dio 使用 #149

Open
reng99 opened this issue Jun 20, 2022 · 0 comments
Open

Flutter 結合 Dio 使用 #149

reng99 opened this issue Jun 20, 2022 · 0 comments
Labels
blog a single blog flutter

Comments

@reng99
Copy link
Owner

reng99 commented Jun 20, 2022

上一篇文章 Flutter 布局备忘录 -- 多图警告,干货建议收藏 中,我们基本了解了 Flutter 相关的布局。那么,我们怎么拿到数据,然后填充到部件中呢?

这里我们使用 Dio 来进行接口的请求。

学过前端的读者应该不陌生,在 package.json 中有下面两种方式引入包:

"dependencies": {
  "@angular/animations": "9.1.11",
},
"devDependencies": {
  "tslint": "~6.1.2",
}

dependencies 下的包是要发布到生产环境,而 devDependencies 下的包只用于开发环境。

flutter 中,pubspec.yaml 也对应着这两个环境,如下:

dependencies:
  flutter:
    sdk: flutter
    
dev_dependencies:
  flutter_test:
    sdk: flutter

这里默认你已经创建一个 Flutter 项目,如果还不清楚如何创建,可以查阅本文 Flutter 系列 - 开始你的第一个应用

因为我们生产环境还是要用到 Dio,所以我们需要在 dependencies 下添加包:

dependencies:
  flutter:
    sdk: flutter
  dio: ^4.0.6

截止发文,Dio 的最新版本为 ^4.0.6

运行 flutter pub get 拉取相关的依赖。如果安装不成功,可尝试另一种安装方法,运行 flutter pub add dio

这里我使用个人站点的接口 「get」 https://jimmyarea.com/api/public/article?page=-1 来调试,你可以复制其接口到浏览器中查看,返回的数据如下:

{
  "code": 0,
  "msg": "ok",
  "data": {
    "results": [
      {
        "meta": {
          "createAt": "2021-08-20T15:20:42.027Z",
          "updateAt": "2021-08-20T15:20:42.027Z"
        },
        "_id": "60a382c4f3a0e93c31a8bd1d",
        "title": "CSS八种让人眼前一亮的HOVER效果",
        "url": "https://juejin.cn/post/6861501624993447950",
        "count": "40000+",
        "thumb": "1300+"
      },
      {
        "meta": {
          "createAt": "2021-08-20T15:20:42.027Z",
          "updateAt": "2021-08-20T15:20:42.027Z"
        },
        "_id": "60a382e9f3a0e93c31a8bd2a",
        "title": "[译]停止滥用div! HTML语义化介绍",
        "url": "https://juejin.cn/post/6844903817968893960",
        "count": "15000+",
        "thumb": "260+"
      },
      {
        "meta": {
          "createAt": "2021-08-20T15:20:42.027Z",
          "updateAt": "2021-08-20T15:20:42.027Z"
        },
        "_id": "60a38317f3a0e93c31a8bd38",
        "title": "10个JS优化小技巧",
        "url": "https://juejin.cn/post/6924108781542440974",
        "count": "12000+",
        "thumb": "240+"
      },
      {
        "meta": {
          "createAt": "2021-08-20T15:20:42.027Z",
          "updateAt": "2021-08-20T15:20:42.027Z"
        },
        "_id": "60a3833bf3a0e93c31a8bd54",
        "title": "两个DIV实现雷达扫描效果",
        "url": "https://juejin.cn/post/6940899696038641700",
        "count": "9000+",
        "thumb": "320+"
      }
    ],
    "current": 1
  }
}

那么我们来验证下在 Flutter 中能否请求到。

我们引入 import 'package:dio/dio.dart' 包后,发起一个请求:

void getArticles() async {
  try {
    Response response;
    response = await Dio().get(
      'https://jimmyarea.com/api/public/article',
      queryParameters: {"page": -1},
    );
    print(response);
  } catch (e) {
    print(e);
  }
}

调用 getArticles(),保存页面之后,在 VSCode 的调试控制台中,你会看到下面的返回:

Dio测试返回的数据.png

还不错是吧,现在我们来回填下获取内容,更改代码如下:

List<Widget> articleWidgets = [];

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    getArticles().then((value) {
      List<Widget> temp = [];
      value['data']['results'].forEach((item) {
        temp.add(Text(item['title']));
      });
      setState(() {
        articleWidgets = temp;
      });
    });
    return Material(
      color: Colors.blue,
      child: SafeArea(
        child: SizedBox.expand(
          child: Card(
            color: Colors.yellowAccent,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: articleWidgets,
            ),
          ),
        ),
      ),
    );
  }

  Future getArticles() async {
    try {
      Response response;
      response = await Dio().get(
        'https://jimmyarea.com/api/public/article',
        queryParameters: {"page": -1},
      );
      return response.data;
    } catch (e) {
      return print(e);
    }
  }
}

上面代码中,我们先通过 getArticles() 函数返回一个类似 promise 的数据,然后在 then 函数中通过 setState 来更新获取的部件,然后渲染到页面。结果如下截图:

写入页面结果.png

Not Bad. 读者可以自行跑起来验证。

@reng99 reng99 added blog a single blog flutter labels Jun 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
blog a single blog flutter
Projects
None yet
Development

No branches or pull requests

1 participant