'Conditionally render widgets based on key/value pair Flutter
I am trying to conditionally render widgets based on a state value in MyApp. My idea was the state value would be an integer (1-3). I would have a Map at the top of my project that looks like this:
Map _widgetType = {
1: WidgetOne(),
2: WidgetTwo(),
3: WidgetThree()
};
And then I have a state value called _type that is initialized at 1. I have a function that updates this value based on a selection from a list of options.
void _toggleClipped(int type) {
setState(() {
_type = type;
});
}
The build looks like the below.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[
Text(
"Hi! I'm Matt!",
style: TextStyle(fontSize: 25),
),
_widgetType[_type],
Text(
"Click the button below to clip image!",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 25))
],
),
),
);
}
The _widgetType[_type] would be the associated widget being rendered based upon the value for _type.
Is this doable in Flutter? I am getting an error saying The values in a const list literal must be constants. Try removing the keyword 'const' from the list literal.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
