问题
I tried using named routes but it doesn't seem it work giving me an error "could not find a generator for route ("/homepage",null) for _MaterialAppState.I couldn't understand the working of namedRoutes in this case.
import 'package:flutter/material.dart';
import './home.dart';
import './auth.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return MyAppState();
}
}
class MyAppState extends State<MyApp> {
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: '/',
routes: {
'/': (BuildContext context) => Auth(),
'/homepage': (BuildContext context) => Home(),
},
);
}
}
//somewhere in auth.dart file
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25.0)),
color: Theme.of(context).accentColor,
child: Column(
children: <Widget>[
Icon(Icons.arrow_forward),
],
),
onPressed: () {
if (_email == "email" && _pass == '123') {
//Navigator.pushReplacementNamed(context,'/homepage');
Navigator.pushReplacement(context, MaterialPageRoute(
builder: (BuildContext context) => Home(),
));
} else {
Scaffold.of(context).showSnackBar(SnackBar(
content:
Text("Please Enter Corrent Login Details"),
action: SnackBarAction(
label: "OK",
onPressed: () {
_controllerEmail.clear();
_controllerPass.clear();
},
),
));
}
},
),
I need it to use the named route
回答1:
You should use:
Navigator.of(context).pushReplacementNamed('/homepage');
Look at the documentation for more details.
EDIT:
Use only 1 material app. Using two material apps (in main.dart and in Auth.dart) leads flutter to search the route in the closest MatertialApp (Auth.dart) and the route definition is in the highest instace (main.dart).
You should remove the MaterialApp from Auth.dart
来源:https://stackoverflow.com/questions/57146482/why-does-it-not-work-when-i-use-pushnamedreplacement-instead-of-pushreplacement