简体   繁体   English

Dart,带有命名参数的构造函数不起作用。 预期位置参数

[英]Dart, constructor with named parameters not working. Positional parameters expected

I am reading a book and I wrote the code exactly as instructed.我正在读一本书,我完全按照说明编写了代码。

 class Contato extends StatelessWidget{

  final String nome;
  final int idade;

  Contato(this.nome, this.idade){

  }

  Widget build(BuildContext buildContext){
    return Text('sou $nome minha idade e´ $idade');
  }

}

I create an instance of this class as this:我创建了这个类的一个实例,如下所示:

  new Contato(nome: 'Monica Alves', idade: 32)

The above code gives me, two positional parameters expected, 0 found.上面的代码给了我,两个预期的位置参数,0 找到。

If you want to specify names for parameters use this如果要为参数指定名称,请使用此

 class Contato extends StatelessWidget{

  final String nome;
  final int idade;

  Contato({this.nome, this.idade}){

  }

  Widget build(BuildContext buildContext){
    return Text('sou $nome minha idade e´ $idade');
  }

}

Then然后

new Contato(nome: 'Monica Alves', idade: 32)

If you don't want the named parameters use this如果你不希望命名参数使用这个

class Contato extends StatelessWidget{

  final String nome;
  final int idade;

  Contato(this.nome, this.idade){

  }

  Widget build(BuildContext buildContext){
    return Text('sou $nome minha idade e´ $idade');
  }

}

Then this那么这个

  new Contato('Monica Alves', 32)

you can change your class like this:你可以像这样改变你的班级:

 class Contato extends StatelessWidget{

  final String nome;
  final int idade;

  Contato({ this.nome, this.idade });

  Widget build(BuildContext buildContext){
    return Text('sou $nome minha idade e´ $idade');
  }
}

OR或者

you can create an object from class like this one:您可以从类中创建一个对象,如下所示:

new Contato('Monica Alves', 32)

new keyword is optional. new关键字是可选的。

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

相关问题 Dart 中的命名参数和位置参数有什么区别? - What is the difference between named and positional parameters in Dart? Dart:Dart如何与Class的Constructor中的命名参数匹配? - Dart: How does Dart match the named parameters in a Constructor of a Class? Dart/Flutter 删除命名构造函数中的样板参数以减少代码大小 - Dart/Flutter remove boilerplate parameters in named constructor to reduce code size 在命名参数中=和:之间的Dart差异 - Dart difference between = and : in named parameters Dart / Flutter 条件命名参数 - Dart / Flutter Conditional Named Parameters 如何在 Dart 中使用命名参数在构造函数初始化列表中创建最终成员变量? - How to create a final member variable in the constructor initialization list using named parameters in Dart? 在运行时选择要包含在 dart class 构造函数中的命名参数 - Choosing which named parameters to include in a dart class constructor at run-time 无法使用可选参数定义构造函数 Dart - Can't define constructor with optional parameters Dart 具有所需参数和 null 安全性的命名构造函数 - Named Constructor with required parameters and null safety 问题:Dart/Flutter 传递参数不起作用 - Question : Dart/Flutter passing parameters not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM