Home > database >  Flutter: What is good practice for making the custom widget?
Flutter: What is good practice for making the custom widget?

Time:12-13

I am confused about good practice between creating the custom widget with the Widget function and the class (stf,stl).

For the example about creating the custom widget with the Widget function:

class FieldCustomWidget {
  static Widget textField(...) {
    return ...;
  }

  static Widget idCardNumberField(...) {
    return ...;
  }

  static Widget phoneField(...) {
    return ...;
  }
}

For the example about creating the custom widget with the class (stf,stl):

class TextFieldCustomWidget  extends StatelessWidget {
  ...
  const TextFieldCustomWidget ({Key? key, ...}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ...;
  }
}
class IdCardNumberFieldCustomWidget  extends StatelessWidget {
  ...
  const IdCardNumberFieldCustomWidget ({Key? key, ...}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ...;
  }
}
class PhoneFieldCustomWidget  extends StatelessWidget {
  ...
  const PhoneFieldCustomWidget ({Key? key, ...}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ...;
  }
}

All customer widgets can use the Widget function or stl because I am using state management. What is good practice? If you have another way, please tell me.

CodePudding user response:

As a general convention don't use functions to create widgets. Here is a discussion if you want to know more details about this.

https://github.com/flutter/flutter/issues/19269

What is the difference between functions and classes to create reusable widgets?

If you are following a functional programming paradigm you can use the functional_widget package.

CodePudding user response:

Follow the official decoding flutter series:

Widgets vs helper methods | Decoding Flutter

  • Related