I'm trying to initialize a variable as a class object and further cast its type based on the parameter passed in the abstract class. However, since as in Dart doesn't accept conditional statement, the approach in the code is failing.
Here the variable is c in the code.
// Abscract class
abstract class MainTabs extends StatelessWidget {
MainTabs(this.useIcon, {Key? key, required this.cls}) : super(key: key);
final bool useIcon;
final String cls;
// Content builder
Widget contentBuilder(int index, Iterable? keys);
// Issue in initializing the variable and casting it
// Controller
late final c = () {
switch (cls) {
case g.hotel:
return HotelsController();
case g.transport:
return TransportController();
default:
return MonumentsController();
}
}() as (cls == g.hotel ? HotelsController : cls == g.transport ? TransportController : MonumentsController);
// Issue here in the line above
@override
Widget build(BuildContext context) => useIcon
? iconView()
: c.ifLoggedIn() ? limitedView(context) : fullView(context);
...
}
// Derived classes
class HotelsPage extends MainTabs {
HotelsPage(useIcon, {Key? key}) : super(useIcon, key: key, cls: g.hotel);
@override
contentBuilder(int index, Iterable? keys) {
...
}
}
class MonumentsPage extends MainTabs {
MonumentsPage(useIcon, {Key? key}) : super(useIcon, key: key, cls: g.monuments);
@override
contentBuilder(int index, Iterable? keys) {
...
}
}
How do I solve this issue? Additionally, my way isn't clean. Instead of a String (cls) and switch statement, I would like to pass the class object itself or as a function and proper casting.
Thanks