Creating your own flutter widgets best practice

Viewed 1015

I am trying to understand the best style for creating your own widgets in flutter, and here are 2 very simplified examples

With the code at the bottom, I can use 1)

new SomeWidget("Some title", someFunction);

or 2)

SomeWidget.widget("Some title", someFunction);

or 3) Some other way I'm not aware of

Method 1) feels more correct (if I've not made some mistakes), however method 2) actually has less code (as I don't need to declare the object variables earlier, assuming I don't need access to context), but I'm wary of static methods.

Is 1) preferred, and why ?

class SomeWidget extends StatelesssWidget {

  String title;
  Function callback;

  SomeWidget( this.title, this.callback );

  //method 1
  Widget build(context) {
    return GestureDetector(
      onTap: callback,
      child: ....some widget
    )
  }

  //method 2
  static Widget widget(String title, Function callback) {
    return GestureDetector(
      onTap: callback,
      child: ....some widget
    )
  }

}
1 Answers

I don't know actual guildelines, but I would prefer something like

class SomeWidget extends StatelesssWidget {

  SomeWidget({this.title, this.callback});

  final String title;
  final VoidCallback callback;

  Widget build(context) {
    return GestureDetector(
      onTap: callback,
      child: ....some widget
    );
  }
}

or you can do like this

SomeWidget({this.title = '', @required this.callback})

for default values or if some value is reqired

P.S. All this is not guideline - it's just an IMHO )

Related