I have a flutter program with 2 stateful widgets I want to switch between, State1 and State2.
I can get it to work if I set State2 as a stateless widget but when I set it to stateful it gives the error "The return type ‘State2’ isn’t a ‘Widget’, as required by the closure’s context."
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp (
const MaterialApp(
home: MyFlutterApp()
),
);
}
class MyFlutterApp extends StatefulWidget {
const MyFlutterApp({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() {
return State1();
}
}
class State1 extends State<MyFlutterApp>{
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: GestureDetector(
onTap: () {
Navigator.of(context).push(CupertinoPageRoute(builder: (context) => State2()));
},
child: const Text("State1")
)
);
}
}
class State2 extends State<StatefulWidget> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: GestureDetector(
child: const Text("State2"),
onTap: () {
Navigator.pop(context);
}
)
);
}
}
2
Answers
You can push/replace the same route passing a parameter, whit this parameter you can make a if for check which state return
Generally you only use a stateful widget to manage some kind of changing variable. This means in this example, state 1 and 2 do not need to be stateful. However, your flutterApp widget could manage what screen it wants to display making that a stateful widget. You wouldnt use pageRoute to navigate to these pages, just render them conditionally.