Home > OS >  Syntax error, related to variable declaration in dart
Syntax error, related to variable declaration in dart

Time:06-20

//SecondMan.dart
class SecondMan extends StatelessWidget{
      String name;
      int age;
      String gender;
      bool isEng;
    
      SecondMan(this.isEng,this.name,this.age,this.gender);


//main.dart
     MaterialPageRoute(
                        builder: (context) => SecondMan(
                             "jame",24, "male",true)),
                  );

it is works but i want to use like

//SecondMan.dart
     class SecondMan extends StatelessWidget{
      String name;
      int age;
      String gender;
      bool isEng;
    
      SecondMan({this.isEng,this.name,this.age,this.gender});



  //main.dart
         MaterialPageRoute(
                            builder: (context) => SecondMan(
                                age: 24, gender: "male", isEng: true)),
                      );

enter image description here

Here, I can use a typical variable, but using square brackets does not pass the variable value of the variable. It is possible for me to use only small brackets and deliver the contents of the variable. But on the Second Man page, I'm trying to use brackets and variables, but I don't know how

CodePudding user response:

Named parameters in Dart are by default optional. This is a problem since that means we are not forced to enter any value and therefore the parameter could ends up being defaulted to a null value.

This is not allowed in Dart code with null-safety enabled since your types are non-nullable by default and therefore not allows null to be a value.

The solution is to either make the variables nullable (put a ? after the type like e.g. String?), specify a default value (like e.g. this.age = 99) or enforce the named parameter with the keyword required like this:

  SecondMan({
    required this.isEng,
    required this.name,
    required this.age,
    required this.gender,
  });

For more details you can read: https://dart.dev/null-safety/understanding-null-safety#required-named-parameters

CodePudding user response:

You can try this way(if you've disabled null safety):

    //SecondMan.dart
    class SecondMan extends StatelessWidget{    

    SecondMan(this.isEng,this.name,this.age,this.gender);

          String name;
          int age;
          String gender;
          bool isEng;
  • Related