uni icon indicating copy to clipboard operation
uni copied to clipboard

Refactor helper functions

Open jlcrodrigues opened this issue 2 years ago • 0 comments

Remove helper functions as described below.

Checklist

  • [x] #806
  • [x] #802
  • [x] #780
  • [ ] #740
  • [x] #739
  • [x] #879
  • [ ] #901
  • [x] #900

Uni Code Guidelines

Helper functions

It's common having to separate widgets inside a build() method. Imagine you are building a card and want to include your very own button. In order to separate concerns, you want to write the code for this button elsewhere, so as to simplify the Card's build method. This can be done one of two ways: creating a helper function and creating a class (better).

Helper function

Many times we take this shortcut as it is faster to implement. This is used all over the application. However, it brings a set of problems, namely impacting performance:

  • If the user triggers a re-draw of your button, this will imply re-drawing the whole widget. As you can imagine, this will become costly for larger widgets.
class MyCard extends StatelessWidget {
    const MyCard({Key? key}) : super(key: key);
    @override
    Widget build(BuildContext context) {
        return Container(
            child: createButton(context),
        );
    }

    Widget createButton(context) {
        // Button is created here
    }

Class Widgets

What we should strive to do is create sub components inside their own separate classes. This will improve performance, sparing CPU utilization. Moreover, class widgets become easier to test and more accurate.

class MyCard extends StatelessWidget {
    const MyCard({Key? key}) : super(key: key);
    @override
    Widget build(BuildContext context) {
        return Container(
            child: MyButton(),
        );
    }

class MyButton extends StatelessWidget {
    const MyButton({Key? key}) : super(key: key);
    @override
    Widget build(BuildContext context) {
        // Button is created here
    }

If you have any doubts refer to this video by the Flutter team.

jlcrodrigues avatar Mar 01 '23 15:03 jlcrodrigues