【问题标题】:5 positional argument(s) expected, but 0 found. Try adding the missing arguments预期有 5 个位置参数,但找到了 0 个。尝试添加缺少的参数
【发布时间】:2021-12-11 01:32:01
【问题描述】:

address_model.dart

class Address {
String placeFormattedAddress;
String placeName;
String placeId;
double latitude;
double longitude;

Address(this.latitude, this.longitude, 
this.placeFormattedAddress,
  this.placeId, this.placeName);
}

这里是 assistant_methods.dart

if (response != "failed") {
  placeAddress = response["results"][0]. 
["formatted_address"];
  Address userPickUpAdress = Address();
  userPickUpAdress.longitude = position.longitude;
  userPickUpAdress.latitude = position.latitude;
  userPickUpAdress.placeName = placeAddress;

  Provider.of<AppData>(context, listen: false)
      .updatePickUpAdress(userPickUpAdress);
}

错误行在第 4 行的 assitant_methods.dart 上,此时我调用了 Address(),并且在下面的代码中我已经初始化了

【问题讨论】:

    标签: flutter dart provider


    【解决方案1】:

    您声明的地址如下:

    Address(
      this.latitude, 
      this.longitude, 
      this.placeFormattedAddress,
      this.placeId, 
      this.placeName,
    );
    

    这意味着在初始化地址时,你必须传递五个参数,为了解决这个问题,你必须做两件事。首先,将参数设为可选,这样您就不必HAVE将它们传递给构造函数。

    Address({
      this.latitude, 
      this.longitude, 
      this.placeFormattedAddress,
      this.placeId, 
      this.placeName,
    });
    

    注意所有可选参数周围的{}

    这意味着您可以不向构造函数传递任何值。但也许更好的解决方案是首先简单地传递值。

    您需要解决的第二个问题是未初始化变量的值。如果您阅读 placeId,您认为会发生什么?你永远不会分配它。它应该抛出一个错误(就像它一样)吗?它应该是一个空字符串吗?它应该为空吗?针对每一个变量问自己这个问题。

    如果变量应该有一个默认值(比如一个空字符串),你可以把它放在构造函数中:

    MyClass({this.myValue: 'default value'});
    

    如果你不传递变量应该抛出错误,你可以保持变量原样,或者在构造函数中添加一个必需的参数。

    MyClass(this.myRequiredVariable, {required this.myOtherRequiredVariable});
    

    最后,如果值应该为空。当你声明变量时。在它的值后面加一个问号表示它可以为空

    class MyClass {
      String? myNullableString;
    }
    

    最后,值得注意的是,这有一个副作用,如果你想从构造函数中初始化一个值,你必须传递它的名字:

    MyClass({this.value});
    
    // when initializing
    // MyClass(10); // this won't work
    MyClass(value: 10); // This will work
    

    如果您不希望这样,请随意将构造函数上的 {} 替换为 [],这也会导致无法使用 required 关键字。

    希望这足以解决问题,但如果我不清楚,请随时询问

    【讨论】:

    • 谢谢伙计,它确实有效!
    【解决方案2】:

    您好 Iamshabell,欢迎来到 SO!

    您正在尝试使用此行上没有任何参数的构造函数:

    Address userPickUpAdress = Address();
    

    但是在你的类上,构造函数参数是强制性的:

    Address(this.latitude, this.longitude, this.placeFormattedAddress, this.placeId, this.placeName);
    

    因此,您需要将它们设为可选项或使用所有参数调用构造函数。

    【讨论】:

      猜你喜欢
      • 2021-12-11
      • 2022-01-19
      • 2022-12-30
      • 2021-05-22
      • 2022-07-25
      • 2021-12-18
      • 2021-07-27
      • 2019-11-03
      • 2021-06-14
      相关资源
      最近更新 更多