0

Coming from Swift this works well in Swift -

class Test {
    let userId: Int?
    let id: Int?
    let title: String?
    
    init(userId: Int, id: Int, title: String) {
        self.id = id
        self.title = title
        self.userId = userId
    }
    
}

Now while trying dart documentation I tried this , it works

class Album {
   int? userId;
  int? id;
  String? title;

    Album({required int userId, required int id, required String title}) {
     this.userId = userId;
     this.id = id;
     this.title = title;
   }
  
}

but if I were to add final keyword which is like let in swift it stops working and I have to do some thing like below -

class Album {
   final int? userId;
   final int? id;
    final String? title;

  
    const Album({required this.id, required this.userId, required this.title});
}

I have no idea why this works and why this below does not - is it just something I have to start doing or is there any logic behind it as well -

class Album {
   final int? userId;
   final int? id;
    final String? title;

    Album({required int userId, required int id, required String title}) {
     this.userId = userId;
     this.id = id;
     this.title = title;
   }
   
}
multiverse
  • 425
  • 3
  • 13
  • See https://stackoverflow.com/q/66725613/. Although that question is about initializing non-nullable members, the answer applies to `final` nullable members as well. – jamesdlin Mar 15 '23 at 07:17

2 Answers2

1

Dart null-safety. You can use late keyword.

class Album {
  late final int? userId;
  late final int? id;
  late final String? title;

  Album({required int userId, required int id, required String title}) {
    this.userId = userId;
    this.id = id;
    this.title = title;
  }
}

But for same name better practice will be

class Album {
  final int? userId;
  final int? id;
  final String? title;
  const Album({
    this.userId,
    this.id,
    this.title,
  });
}

More about null-safety.

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
1

You can use an initializer list to initialize final variables outside the constructor like this:

class Album {
  final int? userId;
  final int? id;
  final String? title;

  Album({required int userId, required int id, required String title}) :
    this.userId = userId,
    this.id = id,
    this.title = title;

}

But for this example you really should just write it as

class Album {
  final int? userId;
  final int? id;
  final String? title;

  Album({required int this.userId, required int this.id, required String this.title});

}

This is more idiomatic, more concise. There's no reason to write it the other way.

Ivo
  • 18,659
  • 2
  • 23
  • 35