我正在学习 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}.');
}
}
这是我的代码有错误的图像:
首先将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';
}
如果仍然不起作用,请尝试以下操作:
import 'package:http/http.dart';
var response = get(Uri.parse('https://www.google.com'));
试试这个(将 http 添加到依赖项下的 pubspec.yaml 中):
import 'package:http/http.dart' as http;
var response = http.get(Uri.parse('https://www.google.com'));
您传递的字符串错误表明需要一个 uri,因此创建一个 uri 并在其中使用。
var uri = new Uri.http("example.org", "/path", { "q" : "{http}" });
首先,检查您的 pubspec.yaml 文件和 HTTP 版本。它应该是您可以在这里找到的实际版本:https://pub.dev/packages/http/install 比如是:
http: ^0.12.2
此刻
这是我的代码,它运行良好:
main.dart
import 'package:flutter/material.dart';
import 'package:stackowerflow/my_app.dart';
void main() {
runApp(MyApp());
}
my_app.dart
import 'dart:convert' as convert;
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class MyApp extends StatelessWidget {
Future<void> stackHelp() async {
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);
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}.');
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter WebView '),
),
body: Container(
child: TextButton(onPressed: stackHelp, child: Text('Push me')),
),
),
);
}
}
结果
flutter: Number of books about http: 485.