Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter: Using a Builder method as a way to declare variables inside a widget

Consider the following widget:

class MainWidget extends StatelessWidget {
  const MainWidget({super.key});

  @override
  Widget build(BuildContext context) {
    bool condition1 = true;

    return Column(
      children: [
        // inserting widget1 based on condition1
        if (condition1) ...[
          Builder(
            // creating a Builder widget in order to decalre 'condition2'
            builder: (context) {
              bool condition2 = true; // just an example, not actual value
              return condition2 ? const MyWidget2() : const MyWidget3();
            },
          )
        ]
      ],
    );
  }
}

I’m trying to display different widgets based on conditions. I wrap the widgets inside a Builder since I want to be able to declare the variables inside the nested widget (No, they can’t be declared higher up in the widget tree).

The question is, whether this is the right way to do that? Because what if you have a BlocBuilder for example, and you listen for a certain state of ‘success’, BUT within than state you could either show the items or something else? I can’t think of another way to declare variables in such a scenario.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, it’s totally fine with your idea. If you want your code to be clearer, you can create a new widget and put the condition in the in the build method.
For example

class ConditionWidget extends StatelessWidget {
  const MainWidget({super.key});

  @override
  Widget build(BuildContext context) {
    bool condition2 = true;
    return condition2 ? const MyWidget2() : const MyWidget3();
  }

and then in the MainWidget

class MainWidget extends StatelessWidget {
  const MainWidget({super.key});

  @override
  Widget build(BuildContext context) {
    bool condition1 = true;

    return Column(
      children: [
        // inserting widget1 based on condition1
        if (condition1) ...[
          ConditionWidget()
        ]
      ],
    );
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading