Flutter Tutorial
Install Flutter in Win/Linux/Mac
Flutter Widgets:
Bottom Navigation Bar in Flutter
Auto Close Keyboard in Flutter
Screen size handling in Flutter
Flutter REST API
Flutter Advance
Wrap vs Builder vs OverBarFlow
Circular progress contain Icon
Flutter State management Comparison
Flutter Database
Flutter Token Expired Handling
Flutter Provider
Flutter GetX
Flutter with Native
Flutter Tips
Interview Questions
Flutter Switch Cases
Switch cases can also be used for widgets, sometimes multiple widgets that will appear when a specific case occurs, to deal with this we can use switch cases. In the example below, we are using a switch statement to conditionally create different widgets based on the value of a variable.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final int selectedOption = 2; // Replace this with your actual value or in this case OptionTwoWidget will display information in the body
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Switch Cases Example',
home: Scaffold(
appBar: AppBar(
title: Text('Switch Cases Example'),
),
body: buildWidgetBasedOnOption(selectedOption),
),
);
}
// Here, this is switch case for widgets
Widget buildWidgetBasedOnOption(int option) {
switch (option) {
case 1:
return OptionOneWidget();
case 2:
return OptionTwoWidget();
case 3:
return OptionThreeWidget();
default:
return DefaultWidget();
}
}
}
// below are the options
class OptionOneWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text('Option One Widget'),
);
}
}
class OptionTwoWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text('Option Two Widget'),
);
}
}
class OptionThreeWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text('Option Three Widget'),
);
}
}
class DefaultWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text('Default Widget'),
);
}
}