Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter/dart and static Widget methods. bad pattern?

Tags:

flutter

dart

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?

like image 469
johndoe82 Avatar asked Oct 28 '25 08:10

johndoe82


2 Answers

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.

like image 127
Jay Mungara Avatar answered Oct 29 '25 23:10

Jay Mungara


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).

like image 27
Randal Schwartz Avatar answered Oct 29 '25 23:10

Randal Schwartz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!