Skip to content

Support shorthand class creation syntax #1002

Closed
@agrosner

Description

@agrosner

For classes with a single constructor that takes in a few values.

class User {
  final String firstName;
  final String lastName;

  User({@required this.firstName, @required this.lastName});
}

It would be much cleaner and concise to simply allow a "primary constructor":

class User({@required this.firstName, @required this.lastName}) {
  final String firstName;
  final String lastName;
}

Duplicating constructor and class declaration seems a little clunky. When we have more fields,
this duplication is further known and wish we could take it a step further to allow:

class User({@required final String firstName, @required final String lastName});

Less duplication in code will lead to nice details in our widgets for flutter like from this:

class AppDetails extends StatefulWidget {
  final String url;
  final String jobName;

  AppDetails({@required this.url, @required this.jobName});

  @override
  AppDetailsState createState()  => new AppDetailsState(this.url, initialJobName: jobName);
}

class AppDetailsState extends State<AppDetails> {
  String selectedJobName;
  final String jobUrl;

  AppDetailsState(this.jobUrl, {@required String initialJobName}) {
    this.selectedJobName = initialJobName;
  }

  // state implementation below

}

to this:

class AppDetails({@required final String url, @required final String jobName})
 extends StatefulWidget {
  @override
  AppDetailsState createState() => new AppDetailsState(this.url, initialJobName: jobName);
}

class AppDetailsState(final String jobUrl, {@required String initialJobName}) 
 extends State<AppDetails> {

  // state implementation below

from 17 lines of boilerplate to 8.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problems

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions