简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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