In Flutter, managing multiple widgets dynamically can be achieved using a Switch statement. The examples below illustrate how to leverage a Switch statement to conditionally select and display widgets based on specific requirements. This technique is particularly useful when the choice of widget depends on dynamic conditions, and a switch case construct provides an organized and readable way to handle such scenarios.
Switch case Widget Example
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final int _widgetType = 2; // Change this value to switch between widgets
@override
Widget build(BuildContext context) {
Widget selectedWidget;
switch (_widgetType) {
case 1:
selectedWidget = WidgetOne();
break;
case 2:
selectedWidget = WidgetTwo();
break;
case 3:
selectedWidget = WidgetThree();
break;
default:
selectedWidget = Container(color:Colors.red, child:Text("Default"); // A default widget if no case matches
}
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Switch Case Example'),
),
body: Center(
child: selectedWidget,
),
),
);
}
}
class WidgetOne extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Text('Widget One'),
);
}
}
class WidgetTwo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Text('Widget Two'),
);
}
}
class WidgetThree extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Text('Widget Three'),
);
}
}
Second Example Switch case Widget:-
This is a generic example that you can customize based on your specific needs. Simply pass an index value, and for instance, if the index is 0, instantiate and use WidgetOne();
Widget switchCaseToUseSingleWidget(index){
try{
switch (index) {
case 1:
return WidgetOne();
case 2:
return WidgetTwo();
case 3:
return WidgetThree();
default:
return Container(
color:Colors.red,
child:Text("Default"); // A default widget if no case matches
}
}
catch(exception){
return Container(
color:Colors.red,
child:Text("Default");
}
}