4

I have a ui.dart file and UIBuilder.class in it:

class UI {

  static Widget buildButton(String text, VoidCallback onPressed, {double width, ...}) {
    return SizedBox(
        width: width,
        child: RaisedButton(
             ...
            onPressed: onPressed));
  }

  ... 
  static Widget buildOtherWidget(...)
  ....

}

Then just call it in a lot of Screen/Page:

var btn = UI.buildButton(..);

Is it a bad pattern in flutter/dart? If yes, how can I change it?

johndoe82
  • 41
  • 6
  • See also: https://stackoverflow.com/questions/53234825/what-is-the-difference-between-functions-and-classes-to-create-reusable-widgets/53234826#53234826 – Syed Ali Mar 10 '23 at 22:01

4 Answers4

2

I think it can be much more efficient if you are creating a separate file for creating all your reusable widgets like,

import 'package:flutter/material.dart';

Widget buildButton(String text, VoidCallback onPressed, {double width, ...}) {
    return SizedBox(
        width: width,
        child: RaisedButton(
             ...
            onPressed: onPressed));
  }

Widget buildSecondWidget(){
// block of code 
}

Widget buildThirdWidget(){
// block of code 
}

This way you can as many global widgets you want. You just need to import this file and you can access any of the reusable widget and there will be not a static reference throughout the app lifecycle.

So i think approach will be more efficient than creating stateful widgets inside a class.

Jay Mungara
  • 6,663
  • 2
  • 27
  • 49
  • so basically I need to remove the UIBuilder class from the header and all static word, and thats it? And perhaps refactor the code when I used UiBuilder.buildAnything to buildAnything... – johndoe82 Jan 07 '20 at 13:33
1

It's not clear to me if this perhaps breaks the change detection. If you break the change detection, you'll get either very inefficient code (too many builds) or broken code (not enough builds).

Randal Schwartz
  • 39,428
  • 4
  • 43
  • 70
0

no this could not be a bad pattern as it's not a bad pattern to create a custom widget. both your helper static methods and custom widgets are just creating a new instance of a widget. so it is completely fine to use static methods to create new widgets all over your app screens

alireza easazade
  • 3,324
  • 4
  • 27
  • 35
0

As long as your static methods are pure functions, it is not a bad practice to do this.

Kalpesh Kundanani
  • 5,413
  • 4
  • 22
  • 32