import 'package:dio/dio.dart';
import 'dart:async';
import 'dart:io';
import 'package:share/system/Object_category.dart';
enum Method { get, post }
const baseURL = "xxxxxxx";你的域名地址
const getSwiperURL = baseURL + "Swiper/ls";
const getUserInfoURL = baseURL + "User/get_info";
const postTaskURL = baseURL + "Task/create_task";
Future sendRequest(String url, Method method, Map<String, dynamic> map) async {
try {
print("开始请求数据");
Response response;
Dio dio = new Dio();
dio.options.contentType =
ContentType.parse("application/x-www-form-urlencoded").toString();
var type = method;
switch (type) {
case Method.get:
print('开始使用get');
response = await dio.get(url, queryParameters: map);
break;
case Method.post:
print('开始使用post');
FormData formData = FormData.fromMap(map);
response = await dio.post(url, data: formData);
break;
}
if (!empty(response.data)) {
print('收到返回信息==>' + response.data);
}
if (response.statusCode == 200) {
return response.data;
} else {
throw Exception('后端接口出现异常');
}
} catch (e) {
return print('error');
}
}
这个是用法
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
title: Text("我的"),
),
backgroundColor: Colors.white,
body: FutureBuilder(
future: sendRequest(getUserInfoURL, Method.post, {'uid': 100}), //第一个参数是api地址,第二个是post请求,第三个是数据
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
var obj = json.decode(snapshot.data.toString());
String username = obj['data']['nickname'];
String url = obj['data']['avatar'] == null
? ''
: obj['data']['avatar'];
return ListView(
children: <Widget>[
_topHeader(username, url),
_actionList(),
],
);
} else {
return Container(
alignment: Alignment.center, child: Text('加载失败请重新加载'));
}
} else {
return Container(
alignment: Alignment.center,
child: CircularProgressIndicator());
}
}));
}
}
一般的使用方法
sendRequest(postTaskURL, Method.post, map).then((value) {
print(value);
var obj = json.decode(value.toString());
if (obj['code'] == 1) {
print(obj['data']);
//成功之后这边做相应的操作
}
}).catchError((error) {
if (error) {
print(error.toString());
}
});
网友评论