线上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("加载中"));
          }
        },
      ),
    );
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐