flutter之从零搭建小米商城APP(四)http封装(dio)

1.添加依赖

根目录下找到pubspec.yaml,这里用的dio,还蛮好用的,自己去dio官网找到版本,填上去保存就会自动下载
在这里插入图片描述

2.封装Http

根目录新建http文件夹,新建index.dart文件
在这里插入图片描述
index.dart

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class Http {
  static BaseOptions options = BaseOptions(
      baseUrl: 'https://m.mi.com/v1/',
      connectTimeout: 60000,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Referer': 'https://m.mi.com/'
      });

  static Dio dio = Dio(options);

  static get(
      {@required String path,
      Map<String, String> data = const {},
      options}) async {
    try {
      Response response = await dio.get(path, queryParameters: addParam(data));
      return response.data;
    } on DioError catch (e) {
      formatError(e);
    }
  }

  static post(
      {@required String path,
      Map<String, String> data = const {},
      options}) async {
    try {
      Response response = await dio.post(path, queryParameters: addParam(data));
      if (response.statusCode == 200) {
        return response.data['data'];
      }
    } on DioError catch (e) {
      formatError(e);
    }
  }

  static Map addParam(Map<String, String> data) {
    data['client_id'] = "180100031051";
    data['webp'] = "1";
    return data;
  }

  /*
   * error统一处理
   */
  static void formatError(DioError e) {
    if (e.type == DioErrorType.CONNECT_TIMEOUT) {
      // It occurs when url is opened timeout.
      print("连接超时");
    } else if (e.type == DioErrorType.SEND_TIMEOUT) {
      // It occurs when url is sent timeout.
      print("请求超时");
    } else if (e.type == DioErrorType.RECEIVE_TIMEOUT) {
      //It occurs when receiving timeout
      print("响应超时");
    } else if (e.type == DioErrorType.RESPONSE) {
      // When the server response, but with a incorrect status, such as 404, 503...
      print("出现异常");
    } else if (e.type == DioErrorType.CANCEL) {
      // When the request is cancelled, dio will throw a error with this type.
      print("请求取消");
    } else {
      //DEFAULT Default error type, Some other Error. In this case, you can read the DioError.error if it is not null.
      print("未知错误");
    }
  }
}

至于api.dart,接口的封装。

const HOME_PAGE = '/home/page';

3.使用

home.dart

import 'package:flutter/material.dart';
import 'package:mi_shop/components/HeaderNav.dart';
import 'package:mi_shop/http/index.dart';
import 'package:mi_shop/http/api.dart';
import 'package:mi_shop/components/Nav.dart';

class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new Page();
  }
}

class Page extends State<Home> {
  Map pageData = Map();
  @override
  void initState() { // 会自动调用,生命周期
    requestAPI();
  }

  @override
  Widget build(BuildContext context) {
    return layout(context);
  }

  Widget layout(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
          // appBar: new AppBar(
          //   title: new Text('Welcome to Home'),
          // ),
          body: new Container(
        child: new Column(
          children: <Widget>[
            new HeaderNav(
                left: Container(
                  child: Image(
                    image: new AssetImage('images/logo.png'),
                    height: 15,
                  ),
                ),
                content: Container(
                  decoration: new BoxDecoration(
                      border:
                          new Border.all(width: 1, color: Color(0xffe5e5e5)),
                      borderRadius: BorderRadius.all(Radius.circular(2.0))),
                  child: Scaffold(
                    body: Row(
                      children: <Widget>[
                        Container(
                          child: Icon(Icons.search,
                              color: Color(0x4D000000), size: 20),
                          margin: EdgeInsets.fromLTRB(5, 0, 3, 0),
                        ),
                        Expanded(
                          child: new TextField(
                            decoration: new InputDecoration(
                              hintText: '搜索商品名称',
                              hintStyle: new TextStyle(
                                  fontSize: 13.0, color: Color(0x4D000000)),
                              fillColor: Colors.white, // 背景颜色
                              filled: true, // 支持背景颜色
                              contentPadding:
                                  const EdgeInsets.symmetric(vertical: 4),
                              border: OutlineInputBorder(
                                  borderSide: BorderSide.none,
                                  // borderSide: BorderSide(color: Color(0xffe5e5e5)),
                                  borderRadius: BorderRadius.circular(3)),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                right: Container(
                  child: Image(
                    image: new AssetImage('images/user.png'),
                    height: 18,
                  ),
                )),
            new Nav(tabs: pageData)
          ],
        ),
      )),
    );
  }

  void requestAPI() async {
    // 请求API数据
    var res = await Http.post(path: HOME_PAGE, data: {'page_type': 'home'});
    setState(() { // 发生改变时更新
      pageData = res;
    });
  }
}

Nav.dart

import 'package:flutter/material.dart';

class Nav extends StatefulWidget {
  final Map tabs;
  Nav({Key key, this.tabs}) : super(key: key);
  @override
  createState() => new MyComponent();
}

class MyComponent extends State<Nav> {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
        height: 100,
        child: new ListView(
            scrollDirection: Axis.horizontal, children: handlerData()));
  }

  List<Widget> handlerData() {
    List<Widget> items = [];
    if (widget.tabs != null) {
      for (var item in widget.tabs['tabs']) {
        items.add(new Container(
          child: new Text(item['name']),
        ));
      }
    }
    return items;
  }
}

Nav是封装组件,在components下
在这里插入图片描述

发布了46 篇原创文章 · 获赞 8 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/yuanqi3131/article/details/103875081
今日推荐