英文:
how to i get data with multiple parametres while get data from api to flutter
问题
我想在Flutter中的RESTful API中使用多个参数。
我可以按ID获取数据,但我想按ID和UserID获取数据。
我该怎么做?
class NetworkService {
Future<List<dynamic>> fetchData(int id) async {
final response = await http.get(Uri.parse
("https://jsonplaceholder.typicode.com/posts?id=$id"));
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
print("无法加载数据");
}
}
}
英文:
i want to use multiple parametres for restful api in flutter.
i can get data by id but i want to get data by id and userId.
how could i do?
class NetworkService {
Future<List<dynamic>> fetchData(int id) async {
final response = await http.get(Uri.parse
("https://jsonplaceholder.typicode.com/posts?id=$id"));
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
print("Failed to load data");
}
}
}
答案1
得分: 0
你可以这样做
class NetworkService {
Future<List<dynamic>> fetchData(int id, int userId) async {
final response = await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts?id=$id&userId=$userId"));
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
print("加载数据失败");
}
}
}
英文:
You could do this
class NetworkService {
Future<List<dynamic>> fetchData(int id, int userId) async {
final response = await http.get(Uri.parse
("https://jsonplaceholder.typicode.com/posts?id=$id&userId=$userId"));
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
print("Failed to load data");
}
}
}
</details>
# 答案2
**得分**: 0
以下是您要翻译的内容:
```dart
Future<List<dynamic>> fetchData(int id, int userId) async {
Map parameters = {"id": id, "userId": userId};
final request = Request('GET', Uri.parse("https://jsonplaceholder.typicode.com/posts"));
request.headers['content-type'] = 'application/json';
request.body = json.encode(parameters);
final response = await request.send();
final res = await Response.fromStream(response);
if (res.statusCode == 200) {
return jsonDecode(res.body);
} else {
print("Failed to load data");
}
}
如果您有任何其他需要,请随时提出。
英文:
Try the following
Future<List<dynamic>> fetchData(int id, int userId) async {
Map parameters = {"id": id, "userId": userId};
final request =
Request('GET', Uri.parse("https://jsonplaceholder.typicode.com/posts"));
request.headers['content-type'] = 'application/json';
request.body = json.encode(parameters);
final response = await request.send();
final res = await Response.fromStream(response);
if (res.statusCode == 200) {
return jsonDecode(res.body);
} else {
print("Failed to load data");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论