flutter实战项目03 dio之异步请求

线上mock数据模拟地址
https://www.fastmock.site/mock/18e030d9e667d42b22dc9abd9637b30b/flutter/indexPage
异步请求地址配置示例
config/http_conf.dart

const base_url = "https://www.fastmock.site/mock/18e030d9e667d42b22dc9abd9637b30b/flutter";
const servicePath = {
  "homePageServer": base_url + '/indexPage'
};

异步公用方法示例
service/http_service.dart 引入dio相关插件

import "package:dio/dio.dart";
import "dart:async";
import "dart:io";
import "../config/index.dart";

Future request(url, {formData}) async {
  try {
    Response response;
    Dio dio = new Dio();
    dio.options.contentType = ContentType.parse('application/x-www-form-urlencoded');
    if(formData == null){
      response = await dio.post(servicePath[url]);
    } else {
      response = await dio.post(servicePath[url],data: formData);
    }
    response = await dio.get(servicePath[url]);
    if(response.statusCode == 200){
      return response;
    } else {
      throw Exception('${KeyString.httpError}');
    }
  } catch(e){
    return print('error:::${e}');
  }
}

页面请求

return Scaffold(
      backgroundColor: Color.fromARGB(244, 245, 245, 1),
      appBar: AppBar(title: Text('异步请求')),
      body: FutureBuilder(
        future: request('homePageServer',formData: null),
        builder: (context, snapshot){
          if(snapshot.hasData){
            var data = json.decode(snapshot.data.toString());
            List<Map> swiperDataList = (data['data']['slides'] as List).cast();
            return Container(child: Text("${data}"));
          }else{
            return Container(child: Text("加载中"));
          }
        },
      ),
    );

猜你喜欢

转载自blog.csdn.net/weixin_45561719/article/details/107890121