错误:无法将参数类型“String”分配给参数类型“Uri”。 - 'Uri' 来自 'dart:core'

时间:2021-05-21 22:08:21

标签: android string flutter localhost uri

我有这个错误的问题:

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

import 'package:inboxed/model/login_model.dart';

class APIService {
  Future<LoginResponseModel> login(LoginRequestModel requestModel) async {
    String url = 'https://localhost:3000/api/users/session';

    final response = await http.post(url, body: requestModel.toJson());
    if (response.statusCode == 200 || response.statusCode == 400) {
      return LoginResponseModel.fromJson(
        json.decode(response.body),
      );
    } else {
      throw Exception('Failed to load Data');
    }
  }
}

调试控制台:

在调试模式下在 IA 模拟器上的 AOSP 上启动 lib\main.dart...

lib/api/api_service.dart:10:38: 错误:无法将参数类型“String”分配给参数类型“Uri”。

Uri' 来自 'dart:core'。 最终响应 = await http.post(url, body: requestModel.toJson());

FAILURE:构建失败,出现异常。

哪里: 脚本 'C:\development\flutter\packages\flutter_tools\gradle\flutter.gradle' 行:991

出了什么问题: 任务 ':app:compileFlutterBuildDebug' 执行失败。 Process 'command 'C:\development\flutter\bin\flutter.bat'' 以非零退出值 1 结束

试试: 使用 --stacktrace 选项运行以获取堆栈跟踪。使用 --info 或 --debug 选项运行以获得更多日志输出。使用 --scan 运行以获得完整的见解。

https://help.gradle.org

获得更多帮助

构建在 38 秒内失败 例外:Gradle 任务 assembleDebug 失败,退出代码为 1 退出(sigterm)

2 个答案:

答案 0 :(得分:0)

需要用下面的代码解析你的网址并传递这个而不是网址字符串;

Uri.parse(url)

使用示例代码 ;

String url = "https://sandbox-api.iyzipay.com/payment/bin/check";
  Map body = {"locale":"tr","conversationId":"123456ayx5","binNumber":"$binNumber"} ;

  //String 
  String requeststr = "locale=tr,conversationId=123456ayx5,binNumber=$binNumber";

  String pkistring = v1hashing(requeststr);

  HttpClient httpClient = new HttpClient();
  HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));

//headers
  request.headers.set('Accept' ,  'application/json');
  request.headers.set('Content-Type' ,  'application/json');


//body
  request.add(utf8.encode(json.encode(body)));

//response 
  HttpClientResponse response = await request.close();
  print(response.statusCode); 
  String reply = await response.transform(utf8.decoder).join();
  Map responseMap = json.decode(reply);
  httpClient.close();
  print(responseMap);

答案 1 :(得分:0)

只需解析带有 Uri 的 String url.... 看下面的例子

String url = "your_endpoint_here";
final response = await http.post(Uri.parse(url), body: requestModel.toJson());