Finley Adams
Finley Adams

Reputation: 831

Initialize object with final instances dart

If I have this class :

class Person {
  Person(
      @required this.name,
      @required this.age,
      @required this.job,
  });
  final String name;
  final int age;
  final String job;
  );

How can I create an object that has all these properties but set by me before the use? Something like :

Person william(name : 'William', age : 25, job : 'officer');
doSomething(william);

Upvotes: 0

Views: 217

Answers (1)

bluenile
bluenile

Reputation: 6029

Please see the code below :

   void main() {
      final Person william = Person(name:"William", age:25, job:"officer");
      doSomething(william);
    }
    
    void doSomething(Person person) {
      print('${person.name} ${person.age} ${person.job}');
    }
    
    class Person {
      Person({
        this.name,
        this.age,
        this.job,
      });
    
      final String name;
      final int age;
      final String job;
    }

Upvotes: 1

Related Questions