flutter / flutter-intellij

Flutter Plugin for IntelliJ
https://flutter.dev/using-ide
BSD 3-Clause "New" or "Revised" License
1.98k stars 319 forks source link

Proposal: Offer a "copy with" generate option #4878

Open matthew-carroll opened 4 years ago

matthew-carroll commented 4 years ago

Pressing ctl+enter in Android Studio brings up a menu with auto-generation options. This is often used to generate == and hashCode methods.

In Flutter there is often a need for a copyWith method, which is used to duplicate an existing data structure with some number of alterations. For example:

myTheme.copyWith(
  brightness: Brightness.dark,
  primaryColor: Colors.yellow,
);

A copyWith method might look like:

class MyThing {
  const MyThing({
    this.itemA,
    this.itemB,
    this.itemC,
 });

 final String itemA;
 final int itemB;
 final bool itemC;

 MyThing copyWith({
   String thingA,
   int thingB,
   bool thingC,
}) {
  return MyThing(
    thingA: thingA ?? this.thingA,
    thingB: thingB ?? this.thingB,
    thingC: thingC ?? this.thingC,
  );
}

I think it would be a good idea to add a generation option for a copyWith method, with a generator that would look and operate almost identically to that of == and hashCode.

devoncarew commented 4 years ago

Do these methods typically exist on Flutter framework classes? Objects used by the framework? Widget classes?

I want to make sure that we don't over-offer this option - that we don't offer it for every type of class, if that ends up being too noisy.

matthew-carroll commented 4 years ago

It makes sense for any immutable data structure, e.g., ThemeData. I'm not sure how one would differentiate a class it applies to and a class it doesn't apply to, but that's the target.

KlausJokisuo commented 4 years ago

Many people use code generation for this kind of stuff. Freezed package is probably the most popular one. Just an FYI using code generation can "break" the Dart analyzer so it will show old errors instead of correct ones. Here is an issue regarding the problem https://github.com/dart-lang/sdk/issues/43166

Also if this comes supported, then fromJson and toJson methods should be implemented as well.