5

When I auto generate dart constructors, I would like the generator to make my constructors using named parameters and add key.

(Curly braces wrapping the constructor arguments)

Is there some easy trick I can perform to make Android Studio do this for me?

// Auto generated constructor without named parameters. 
// This is how Android studio currently generates my Widget constructors.
class MyTestModel {
  MyTestModel(this.a, this.b, this.c);

  final String a;
  final String b;
  final String c;
}

// Constructor with named parameters and key.
// This is how I would like Android Studio Auto Generate to behave.
class MyTestModelB {
  MyTestModelB({Key key, this.a, this.b, this.c}) : super(key: key);

  final String a;
  final String b;
  final String c;
}

So another way to phrase my question:

When I press "Command + N" and I use Android Studio to automatically generate my Dart constructor.

Currently Android Studio does not generate Named Parameter Constructors for me, neither does it add a key to the constructors.

Somewhere I guess there is a Template of some kind that Android Studio uses to autogenerate those constructors. I guess I need to access that Template and modify it to have it autogenerate Named Parameter Constructors for me, and add key. But where is it?

My installation of Flutter/Dart/Android studio is rather new. From April/May 2020.

Rune Hansen
  • 954
  • 3
  • 16
  • 36

3 Answers3

3

The default constructor generator from Cmd+N (MacOS) will not generate named parameters constructor. You need to highlight one of your final variable (must be final), wait for the popup (see video clip) and select generate constructor from final field or press alt+shift+enter.

Lee Chee Kiam
  • 11,450
  • 10
  • 65
  • 87
3

If you are looking for the 'named argument constructor' option in the generate menu, then you should install Dart Data Class Plugin.

-1

Ok, I don't know what has happened to my Android Studio, but now I can generate the constructors like a want them. Something must have happened! Maybe something got installed or updated? I don't know. If you know where exactly the settings for auto generate of Flutter constructors happens in Android Studio, I am interested to know. This is how my constructors look now:

class Avatar extends StatelessWidget {
  final String photoUrl;
  final VoidCallback onPressed;
  const Avatar({Key key, this.photoUrl, this.onPressed}) : super(key: key);
}
Rune Hansen
  • 954
  • 3
  • 16
  • 36