所以这是我第一次尝试与扑动。我来自Angular,在那里,依赖注入让路由变得轻而易举。只要把Router注入到任何服务中就可以了。以下是我的flutter应用程序的场景:
在"/login"页面我点击登录按钮。这将从Auth提供程序调用方法,其中在验证凭据后,应用程序应路由到'/home'。
这就是我无法理解的事情,即使我在网上读了所有可能的帖子。每个人都说应该用ChangeNotifierProvider包装MaterialApp我做错了什么?
这是我的代码。你能告诉我正确的方向吗?import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => Auth(context: context),
child: MaterialApp(
initialRoute: "/login",
routes: {
"/login": (context) => LoginPage(),
"/home": (context) => HomePage()
},
),
);
}
}
//This is my Login page Widget - After successful login I want to be able to use Navigator to push to '/home' route
class LoginPage extends StatelessWidget {
@override
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Login"),
),
body: ElevatedButton(
//
onPressed: () => {
// here I want to use login method on Auth provider. Which should validate credentials and if valid redirect to home page
Provider.of<Auth>(context, listen: false).login()
},
child: Text("login"),
));
}
}
//This is my Home page Widget
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
child: Scaffold(appBar: AppBar(title: Text("Home"))),
);
}
}
//This is my auth controller where After successful login I want to redirect to HomePage
class Auth extends ChangeNotifier {
BuildContext context;
Auth({
required this.context,
});
// This is login method of Auth provider -
login() {
//Here after validating the credentials (eg user / password) I want to redirect to '/home' route.
Navigator.of(context).pushNamed("/home");
}
}
我有一个更好的解决方案,根据身份验证状态改变你的页面路由,在MaterialApp的路由表中做这样的代码:
route:{
'/': (context) => Consumer<AuthProvider>(
builder: (context, value, child) => value.isAuth()
? yourMainPageAfterAuth()
: AuthScreen()}
单斜杠将被视为您的主页,因此在您的身份验证提供程序中验证您的身份验证,然后在身份验证后路由到您的主页
Navigator.of(context).pushNamed('/');