dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.28k stars 1.58k forks source link

avoid_returning_widgets #59498

Open jesperu7 opened 3 months ago

jesperu7 commented 3 months ago

Description: The avoid_returning_widgets rule would ensure that widgets are not returned from functions. Instead, widgets should be created within the build method or in dedicated widget classes. This practice enhances code readability, maintainability, and performance. By enforcing this rule, we can encourage developers to structure their Flutter applications in a more modular and understandable manner.

Rationale:

Maintainability: Keeping widget creation within the build method or dedicated widget classes makes the code easier to maintain. Performance: Proper widget creation helps optimize performance by ensuring that the widget tree is managed efficiently. Clarity: Improves the readability and clarity of the code, making it easier for developers to understand and work with.

Example:

Bad:

Widget createButton() {
  return ElevatedButton(
    onPressed: () {},
    child: Text('Press Me'),
  );
}

Good:

class CustomButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {},
      child: Text('Press Me'),
    );
  }
}
bwilkerson commented 3 months ago

@goderbauer

goderbauer commented 3 months ago

This seems to be a duplicate of https://github.com/dart-lang/sdk/issues/58303. There's some discussion there and what I said there is still accurate.

NatoBoram commented 3 months ago

It's also still addressed in the proposal