在flutter中发出http.get()请求的问题

问题描述

我正在学习 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}.');
  }
}

这是我的代码错误的图像

enter image description here

解决方法

首先将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';
}
,

首先,检查您的 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.

,

您传递的字符串错误提示需要一个 uri,因此创建一个 uri 并在其中使用。

var uri = new Uri.http("example.org","/path",{ "q" : "{http}" });
,

试试这个(将 http 添加到依赖项下的 pubspec.yaml):

import 'package:http/http.dart' as http;

var response = http.get(Uri.parse('https://www.google.com'));