gpt4 book ai didi

flutter - 减少每个模型类的类似HTTP提取方法的重复

转载 作者:行者123 更新时间:2023-12-03 04:43:45 25 4
gpt4 key购买 nike

我以为我已经涵盖了这个问题,但看起来我错了。现在,我需要重做我的所有项目,但是我不确定什么是最好的方法(或通用方法)。到目前为止,我已经有了API_service类,并且可以像这样对后端进行所有可能的调用

class APIService {
Future<List<dynamic>> getByPost(
{String path, Map<String, dynamic> body, String token}) async {
try {
final header =
[APIHeader.authorization(token), APIHeader.json()].reduce(mergeMaps);
final http.Response response =
await http.post(path, headers: header, body: json.encode(body));
final jsonResponse = json.decode(response.body);
if (response.statusCode != 200) {
throw ServerException(jsonResponse["error"]);
}
return jsonResponse['result'];
} catch (error) {
throw error;
}
}
...
}
我得到所有请求的数据库类
class User extends Database with ChangeNotifier {
String _token;

set token(String value) => _token = value;

Future<SeriesModel> getSeries(int id) async {
final response = await APIService()
.getById(path: APIPath.series('get'), token: _token, id: id);
return SeriesModel.fromJson(response);
}
...
}
这种方法的问题在于我的数据库类越来越大,因为我必须为每个调用创建一个新方法。例如,如果我想通过id获取foo,则必须在数据库类中创建新方法getFoo。我知道这不是最好的方法,因此我正在尝试寻找更好的方法。那么构造和重用http调用的常用方法是什么

最佳答案

您可以使用generics减少重复代码。
这是可以在DartPad上运行的Dart示例:

var database = {
{"id": 1, "score": 555, "type": "user"},
{"id": 2, "score": 777, "type": "user"},
{
"id": 3,
"started": DateTime.fromMillisecondsSinceEpoch(1592515515550),
"type": "match"
},
{
"id": 4,
"started": DateTime.fromMillisecondsSinceEpoch(1593513315000),
"type": "match"
},
};

class User {
int id;
int score;
User(this.id, this.score);
User.fromJson(Map<String, dynamic> data)
: id = data["id"],
score = data["score"];
}

class Match {
int id;
DateTime started;
Match(this.id, this.started);
Match.fromJson(Map<String, dynamic> data)
: id = data["id"],
started = data["started"];
}

T getData<T>(int id, T Function(Map<String, dynamic> decoded) creator ) {
Map<String, dynamic> result = database
.singleWhere((dynamic item) => item["id"] == id, orElse: () => null);

// This is where the magic happens. The `creator` function we supplied by the argument
// will create instace of T by using the 'result' as argument.
return creator(result);
}

void main() {
User _user = getData<User>(1, (data) => User.fromJson(data));
Match _match = getData<Match>(4, (data) => Match.fromJson(data));

print(_user.score);
print(_match.started);
}
您也可以使 getData异步。您还可以通过每种方法在 APIService中进行初始化,可以将其设置为工厂。 HTTP客户端也是如此。减少代码中不必要的资源启动量。

关于flutter - 减少每个模型类的类似HTTP提取方法的重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62652629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com