繁体   English   中英

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

[英]Error: The argument type 'String' can't be assigned to the parameter type 'Uri'. - 'Uri' is from 'dart:core'

我有这个错误的问题:

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:错误:无法将参数类型“字符串”分配给参数类型“Uri”。

Uri'来自'dart:core'。 最终响应 = 等待 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 选项运行以获得更多日志 output。 运行 --scan 以获得完整的见解。

https://help.gradle.org获得更多帮助

BUILD FAILED in 38s Exception: Gradle task assembleDebug failed with exit code 1 Exited (sigterm)

需要使用以下代码解析您的 url 并传递它而不是 url 字符串;

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);

只需使用 Uri 解析字符串 url .... 参见下面的示例

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM