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.
>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()
]
],
);
}
}