Here's an example of how you can do a simple implementation of SharedPreferences saving your last route, with named routes. You should be able to modify it to fit your needs:
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: '/',
routes: {
'/': (context) => SharedPrefRoutes65799959(),
'otherView': (context) => OtherView(),
},
),
);
}
class SharedPrefRoutes65799959 extends StatefulWidget {
@override
_SharedPrefRoutes65799959State createState() => _SharedPrefRoutes65799959State();
}
class _SharedPrefRoutes65799959State extends State<SharedPrefRoutes65799959> {
SharedPreferences sharedPreferences;
Navigation navigation = Navigation();
@override
void initState() {
loadLastRoute();
super.initState();
}
loadLastRoute() async {
sharedPreferences = await SharedPreferences.getInstance();
navigation.loadLastRoute(context, sharedPreferences);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Main'),
),
body: Center(
child: RaisedButton(
child: Text('Go to OtherView'),
onPressed: () => navigation.navigateTo(context, 'otherView'),
),
),
);
}
}
class OtherView extends StatefulWidget {
@override
_OtherViewState createState() => _OtherViewState();
}
class _OtherViewState extends State<OtherView> {
Navigation navigation = Navigation();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('OtherView'),
),
body: Center(
child: RaisedButton(
child: Text('Go to Main'),
onPressed: () => navigation.navigateTo(context, '/'),
),
),
);
}
}
class Navigation {
SharedPreferences sharedPreferences;
Navigation(){
loadSharedPreferences();
}
void loadSharedPreferences() async {
sharedPreferences = await SharedPreferences.getInstance();
}
Future<void> navigateTo(context, routeName){
return sharedPreferences.setString('currentRoute', routeName).then((value) {
return Navigator.of(context).popAndPushNamed(routeName);
});
}
Future<void> loadLastRoute(context, sharedPreferences){
String currentRoute = sharedPreferences.getString('currentRoute');
if(currentRoute != null && currentRoute != '' && currentRoute != '/')
return Navigator.of(context).popAndPushNamed(currentRoute);
return null;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…