http库 再次封装的网络请求类 HttpController

1.添加依赖

  1. dependencies:
  2. http: ^0.12.0 #latest version

2.导入库

  1. import 'package:http/http.dart' as http; //导入前需要配置

效果图:

封装类

  1. import 'package:http/http.dart' as http;
  2.  
  3. class HttpController {
  4. static void get(String url, Function callback,
  5. {Map<String, String> params, Function errorCallback}) async {
  6. if (params != null && params.isNotEmpty) {
  7. StringBuffer sb = new StringBuffer("?");
  8. params.forEach((key, value) {
  9. sb.write("$key" + "=" + "$value" + "&");
  10. });
  11. String paramStr = sb.toString();
  12. paramStr = paramStr.substring(0, paramStr.length - 1);
  13. url += paramStr;
  14. }
  15. try {
  16. http.Response res = await http.get(url);
  17. if (callback != null) {
  18. callback(res.body);
  19. }
  20. } catch (exception) {
  21. if (errorCallback != null) {
  22. errorCallback(exception);
  23. }
  24. }
  25. }
  26.  
  27. static void post(String url, Function callback,
  28. {Map<String, String> params, Function errorCallback}) async {
  29. try {
  30. http.Response res = await http.post(url, body: params);
  31.  
  32. if (callback != null) {
  33. callback(res.body);
  34. }
  35. } catch (e) {
  36. if (errorCallback != null) {
  37. errorCallback(e);
  38. }
  39. }
  40. }
  41. }

调用:

  1. import 'dart:convert';
  2. import 'package:flutter/material.dart';
  3.  
  4. import 'package:flutter_test1/http/HttpController.dart';
  5.  
  6. class HomePage extends StatefulWidget {
  7. @override
  8. State<StatefulWidget> createState() {
  9. // TODO: implement createState
  10. return new Page();
  11. }
  12. }
  13.  
  14. class Page extends State<HomePage> {
  15. String dataStr = "";
  16. var _items = [];
  17.  
  18. @override
  19. Widget build(BuildContext context) {
  20. return layout(context);
  21. }
  22.  
  23. @override
  24. void initState() {
  25. super.initState();
  26. getData();
  27. }
  28.  
  29. void getData() {
  30. Map<String, String> map = new Map();
  31. map["v"] = "1.0";
  32. map["month"] = "7";
  33. map["day"] = "25";
  34. map["key"] = "bd6e35a2691ae5bb8425c8631e475c2a";
  35. HttpController.post("http://api.juheapi.com/japi/toh", (data) {
  36. if (data != null) {
  37. final body = json.decode(data.toString());
  38. final feeds = body["result"];
  39. var items = [];
  40. feeds.forEach((item) {
  41. items.add(Model(item["_id"], item["title"], item["pic"], item["year"],
  42. item["month"], item["day"], item["des"], item["lunar"]));
  43. });
  44. setState(() {
  45. dataStr = data.toString();
  46. _items = items;
  47. });
  48. }
  49. }, params: map);
  50. }
  51.  
  52. Widget layout(BuildContext context) {
  53. return new Scaffold(
  54. appBar: buildAppBar(context),
  55. body:
  56. new ListView.builder(itemCount: _items.length, itemBuilder: itemView),
  57. );
  58. }
  59.  
  60. Widget itemView(BuildContext context, int index) {
  61. Model model = this._items[index];
  62. //设置分割线
  63. if (index.isOdd) return new Divider(height: 2.0);
  64. return new Container(
  65. color: Color.fromARGB(0x22, 0x49, 0xa9, 0x8d),
  66. child: new Padding(
  67. padding: const EdgeInsets.all(8.0),
  68. child: new Padding(
  69. padding: const EdgeInsets.all(8.0),
  70. child: new Column(
  71. children: <Widget>[
  72. new Row(
  73. children: <Widget>[
  74. new Text('${model.year}年${model.month}月${model.day}日',
  75. style: new TextStyle(fontSize: 15.0)),
  76. new Text('(${model.lunar})',
  77. style: new TextStyle(fontSize: 15.0)),
  78. ],
  79. ),
  80. new Center(
  81. heightFactor: 6.0,
  82. child: new Text("${model.title}",
  83. style: new TextStyle(fontSize: 17.0)),
  84. )
  85. ],
  86. ))));
  87. }
  88.  
  89. Widget buildAppBar(BuildContext context) {
  90. return new AppBar(title: const Text('历史今日'));
  91. }
  92. }
  93.  
  94. class Model {
  95. String _id;
  96. String title;
  97. String pic;
  98. int year;
  99. int month;
  100. int day;
  101. String des;
  102. String lunar;
  103.  
  104. Model(this._id, this.title, this.pic, this.year, this.month, this.day,
  105. this.des, this.lunar);
  106. }

Flutter -------- Http库 网络请求封装(HttpController)的更多相关文章

  1. flutter dio网络请求封装实现

    flutter dio网络请求封装实现 文章友情链接:   https://juejin.im/post/6844904098643312648 在Flutter项目中使用网络请求的方式大致可分为两种 ...

  2. Flutter学习(7)——网络请求框架Dio简单使用

    原文地址: Flutter学习(7)--网络请求框架Dio简单使用 | Stars-One的杂货小窝 Flutter系列学习之前都是在个人博客发布,感兴趣可以过去看看 网络请求一般APP都是需要的,在 ...

  3. React-Native 之 GD (八)GET 网络请求封装

    1.到这里,相信各位对 React-Native 有所熟悉了吧,从现在开始我们要慢慢往实际的方向走,这边就先从网络请求这部分开始,在正式开发中,网络请求一般都单独作为一部分,我们在需要使用的地方只需要 ...

  4. 十. Axios网络请求封装

    1. 网络模块的选择 Vue中发送网络请求有非常多的方式,那么在开发中如何选择呢? 选择一:传统的Ajax是基于XMLHttpRequest(XHR) 为什么不用它呢?非常好解释配置和调用方式等非常混 ...

  5. Spring Boot + Vue 前后端分离开发,前端网络请求封装与配置

    前端网络访问,主流方案就是 Ajax,Vue 也不例外,在 Vue2.0 之前,网络访问较多的采用 vue-resources,Vue2.0 之后,官方不再建议使用 vue-resources ,这个 ...

  6. 移动开发在路上-- IOS移动开发 五 网络请求封装

    接着上次的讲,这次我们讲 网络请求的封装  打开创建的项目,让我们一起来继续完成他, 上次我们说到GET请求地址的拼接: 我们接着上次的继续完善: 下边我们要定义的是 block //定义block ...

  7. iOS开发——post异步网络请求封装

    IOS中有许多网络请求的函数,同步的,异步的,通过delegate异步回调的. 在做一个项目的时候,上网看了很多别人的例子,发现都没有一个简单的,方便的异步请求的封装例子.我这里要给出的封装代码,是异 ...

  8. Android项目开发全程(三)-- 项目的前期搭建、网络请求封装是怎样实现的

    在前两篇博文中已经做了铺垫,下面咱们就可以用前面介绍过的内容开始做一个小项目了(项目中会用到Afinal框架,不会用Afinal的童鞋可以先看一下上一篇博文),正所谓麻雀虽小,五脏俱全,这在里我会尽量 ...

  9. React Native 网络请求封装:使用Promise封装fetch请求

    最近公司使用React作为前端框架,使用了异步请求访问,这里做下总结: React Native中虽然也内置了XMLHttpRequest 网络请求API(也就是俗称的ajax),但XMLHttpRe ...

随机推荐

  1. SQL server分页的四种方法

    SQL server分页的四种方法 1.三重循环: 2.利用max(主键); 3.利用row_number关键字: 4.offset/fetch next关键字 方法一:三重循环思路  先取前20页, ...

  2. Linux关闭防火墙、设置端口

    关闭防火墙 1)重启后生效 开启: chkconfig iptables on 关闭: chkconfig iptables off 验证防火墙是否关闭:chkconfig --list |grep ...

  3. 二叉树(python)

    # -*- coding: utf-8 -*- from collections import deque class Queue(object): def __init__(self): self. ...

  4. 51nod 2381 个人所得税

    牛牛已知每月的税前收入,他想知道在新个税下,税收后收入是多少?个税计算方法是这样的: 综合所得金额 - 新起征点5000元 = 应纳税所得额 其中 综合所得金额 就是税前收入,(你可以忽略五险一金,专 ...

  5. spring DefaultListableBeanFactory 概述

                 有人说,DefaultListableBeanFactory是spring的发动机,其实重要性不为过.TA的整体类图如下:     这里先概述接口部分:   BeanFact ...

  6. test20190815 NOIP2019 模拟题

    100+60+40=200,被后面两个题卡着我很不爽. 立方数 [问题描述] 作为 XX 战队的狂热粉丝,MdZzZZ 看到了自己心仪的队伍在半决赛落败,顿时 心灰意冷.看着自己手中的从黄牛那里抢来的 ...

  7. sqlite3中给表添加列

    1.修改表名为临时表 ALTER TABLE {tableName} RENAME TO TempOldTable; 2.创建新表,跟原来的表名一致 CREATE TABLE {tableName} ...

  8. Kylin 1 背景、历史与使命

    1.1 背景和历史 今天,大数据领域的发展如火如荼,各种新技术层出不穷,整个生态欣欣向荣.作为大数据领域最重要的技术——Apache Hadoop,从诞生至今已有10周年.它最初只是致力于简单的分布式 ...

  9. MongoDB 查看集合的统计信息

    和 RDBMS 一样, MongoDB 同样存储集合的统计信息,通过调用命令 db.collection.stats() 可以方便的查看集合的统计信息. --1 查看集合 things 的统计信息 r ...

  10. YAML_17 Playbook 综合

    Playbook1.语法特性如下:(1)"---"首行顶格开始(2)#号注释(3)缩进统一,不同的缩进代表不同的级别,缩进要对齐,空格和tab不能混用(4)区别大小写,键值对k/v ...