我想在flutter中创建一个可重用的服务组件,在react-native中,我们可以通过belove代码来实现。
export async function Service({
api,
third_party,
method,
params
}) {
const headers = {};
set(headers, 'Cache-Control', 'no-cache');
set(headers, 'Content-Type', 'application/json');
const reqBody = {
method,
headers,
timeout: 30 * 1000
};
if (!isEmpty(params)) {
reqBody.body = JSON.stringify(params);
}
return fetch(path, reqBody)
.then(response => response.json())
.then((data) => {
console.log('response json data = ', data);
if (data.errors) {
if (data.code === 403 && data.number === 1006) {
emitter.emit('AppRoot:VERSION_UPDATED', data.links);
}
return {
result: 'error',
...data
};
}
return {
result: 'ok',
...data
};
})
.catch(() => {
return {
result: 'error',
message: 'Please check your internet connection!'
};
});
}
使用服务组件。
OpenMed_Service,
{
api: 'patients/add-to-account',
method: 'POST',
params: payload
}
服务.dart
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
class Service extends StatelessWidget {
final String api;
final String method;
var params;
Service({
this.api,
this.method,
this.params
});
var headers = {};
final String url = "http://www.adminapi/somee.com/";
var reqBody = {
'header': ('Content-Type', 'application/json'),
timeout: 30 * 1000
};
if (!isEmpty(params)) {
reqBody.body = json.decode(params);
}
@override
Widget build(BuildContext context) {
if(method == 'post') {
Future<http.Response> createPost(Post post) async{
final response = await http.post('$url',
headers: reqBody.headers,
body: json.encode(post));
return json.decode(response.body);
}
} else if(method == 'get') {
Future<http.Response> getPost() async{
final response = await http.get('$url/$api');
return postFromJson(response.body);
}
}
}
}
我试图创建 statlessWidgets 但得到很多错误。我创建了需要返回小部件的服务类,但我想返回 JSON 数据。
任何人都知道我如何在颤振中存档相同的东西。