skip to Main Content

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;
   }
   
}

2

Answers


  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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search