4

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

}
Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432
Ian
  • 13,724
  • 4
  • 52
  • 75
  • 1
    Your second version doesn't even need or use SomeWidget. It could be a top level function, making SomeWidget redundant. – Richard Heap Nov 09 '18 at 22:35
  • 1
    Ignore the pointless edit. After some thoughts it should have been asked in another question, which I made here: https://stackoverflow.com/questions/53234825/what-is-the-difference-between-functions-and-classes-to-create-widgets/53234826#53234826. This question should answer yours too, go take a look ! :) – Rémi Rousselet Nov 10 '18 at 00:05

1 Answers1

4

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 )

NiklasPor
  • 9,116
  • 1
  • 45
  • 47
Andrii Turkovskyi
  • 27,554
  • 16
  • 95
  • 105
  • 2
    Andrey is right with this one. Anyway, If you have a `StatelessWidget` all fields of the Widget should be immutable e.g. final. If the State of the Widget should be able to change, use a `StatefulWidget`. – NiklasPor Nov 10 '18 at 08:14
  • 1
    You're right, I just missed this moment. Actually, fields in `StatefulWidget` have to be immutable too ) – Andrii Turkovskyi Nov 10 '18 at 09:15
  • Oh, I meant fields in the `State` of the `StatefulWidget`. – NiklasPor Nov 10 '18 at 09:17