我正在学习flutter中的api和http请求,我在get请求时遇到了问题,因为在任何教程中,他们都是直接将字符串url作为参数粘贴到get中,但当我将其作为字符串发布时,它显示错误:参数类型' string‘无法分配给参数类型'Uri’。
有人能在这方面帮我吗:这是我的示例代码:
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
void main(List<String> arguments) async {
// This example uses the Google Books API to search for books about http.
// https://developers.google.com/books/docs/overview
var url = 'https://www.googleapis.com/books/v1/volumes?q={http}';
// Await the http get response, then decode the json-formatted response.
var response = await http.get(url); // i am getting error here
if (response.statusCode == 200) {
var jsonResponse = convert.jsonDecode(response.body);
var itemCount = jsonResponse['totalItems'];
print('Number of books about http: $itemCount.');
} else {
print('Request failed with status: ${response.statusCode}.');
}
}以下是我的错误代码的图像
发布于 2021-04-02 08:35:16
首先将http导入为http
import 'package:http/http.dart' as http;然后使用以下命令解析指向Uri的链接
var url = Uri.parse('https://www.googleapis.com/books/v1/volumes?q={http}');
http.Response response = await http.get(url);
try {
if (response.statusCode == 200) {
String data = response.body;
var decodedData = jsonDecode(data);
return decodedData;
} else {
return 'failed';
}
} catch (e) {
return 'failed';
}发布于 2021-02-26 16:08:01
您传递了字符串,错误提示需要一个uri,因此创建一个uri并在其中使用。
var uri = new Uri.http("example.org", "/path", { "q" : "{http}" });发布于 2021-11-26 00:20:32
如果仍然不起作用,试试这个:
import 'package:http/http.dart';
var response = get(Uri.parse('https://www.google.com'));https://stackoverflow.com/questions/66381021
复制相似问题