so This is my first try with Flutter. I come from Angular where dependency injection made routing a breeze. Just injecting the Router to any service would just do the trick. Here is my scenario for flutter app:
In '/login' page I click Login button. This calls method from Auth provider, where after validating credentials Application should be routed to '/home'.
It's just something I can't wrap my head around even though I read all possible threads in the freaking internet. Everybody said one shoud wrap MaterialApp with ChangeNotifierProvider which I did - what am I doing wrong?
Here is my code. Can you point me to the right direction?
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");
}
}