Access Provider information in Flutter integration test - flutter

I want to access information in one of the Providers used in my app while running integration tests.
I've found some information but doesn't seem to work. I was hoping I could do something like this
User user;
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider.value(value: UsersProvider()),
],
builder: (ctx, child) {
return Consumer<UsersProvider>(
builder: (ctx, usersProvider, _) {
user = usersProvider.user;
return app.MyApp();
},
);
},
),
);
and then after signing in I was hoping to access properties of the User model stored in the Provider such as; user.verificationState.
e.g.
if (user.verificationStatus == VerificationStatus.Verified) {
// Do something based on verification state
}
but my user is always null.

Related

Flutter image assets not loading after redirect with go_router & login

I have a small Flutter app with 2 screens (/login & /home) and I use go_router to navigate and animated_login. The assets are placed on the home screen and they load fine if I directly access the screen, so pubspec.yaml is correctly defined.
The images fail to load only when I redirect to /home after /login. One interesting observation is that when this happens, the Flutter dev server seems to be hanging (stops responding, but doesn't crash, can't restart it with R, the browser tab complains that it lost connection to the server etc.). This problem occurs also with a combination of auto_route and flutter_login.
Thanks for any hints.
Router setup (tried also w/ the redirect parameter at router level rather than individual routes):
GoRouter routerGenerator(UserData userData) {
return GoRouter(
initialLocation: Routes.home,
refreshListenable: userData,
debugLogDiagnostics: true,
routes: [
GoRoute(
path: Routes.home,
builder: (_, __) => BasicScreen(),
redirect: (state) => userData.loggedIn ? null : Routes.login
),
GoRoute(
path: Routes.login,
builder: (_, __) => AnimLoginScreen(),
redirect: (state) => !userData.loggedIn ? null : Routes.home
),
GoRoute(path: '/', builder: (_, __) => BasicScreen())
]);
}
abstract class Routes {
static const home = '/home';
static const login = '/login';
}
Main app:
void main() {
runApp(
MultiProvider(providers: [
//other providers here
ChangeNotifierProvider(create: (_) => UserData()),
], child: MyApp()),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
final router =
routerGenerator(Provider.of<UserData>(context, listen: false));
return MaterialApp.router(
title: 'Playground',
routeInformationParser: router.routeInformationParser,
routeInformationProvider: router.routeInformationProvider,
routerDelegate: router.routerDelegate,
);
}
}
Basic screen:
class BasicScreen extends StatelessWidget {
BasicScreen({super.key});
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
Image(image: AssetImage("assets/images/image1.png")),
Image(image: AssetImage("assets/images/image2.png")),
Image(image: AssetImage("assets/images/image3.png")),
],
),
);
}
}
Solution
Provide a simple proxy over both Flutter DevTool & backend services with SSL capabilities.
Explanation
The issue has nothing to do with routing, but rather the dev setup. Our backend services require SSL connections, but Flutter dev tool doesn't support that. Flow:
Flutter DevTool starts the project (plain HTTP) and opens Chrome window.
Assets load ok.
User logs in, backend service requires HTTPS for secure cookies.
Browser upgrades all localhost connections to HTTPS.
Flutter DevTools fails to provide SSL connection.
Assets fail to load.
The hanging DevTool is caused by the same issue: seems to me that the DevTool is pending the WebSocket connection to be opened by the JS code running in the browser, but as the browser initiates an HTTPS connection to the DevTool, it even fails to load the JS code. Therefore, the DevTool never completes the init process (as it has no incoming connection).

GoRouter - Web - How to detect that the user entered an URL in the browser's address bar?

I'm using go_router on web and I would like to implement a different redirect logic between the call of the go_router's API (push, go, replace) and when the user enters an URL in the browser address bar.
I didn't find any solution and I was going to implement it this way:
If I understood correctly, when the user enters an URL in the browser address bar, it restarts the application from scratch, while calling the API doesn't. And I came to this:
bool _isFirstRedirect = true;
GoRouter(
routes: myRoutes,
redirect: (state) {
if (_isFirstRedirect) {
// Logic when the user enters an URL in the browser's address bar.
_isFirstRedirect = false;
} else {
// Logic when it comes from a call of the go_router's API.
}
},
);
But I'm not sure that is a good design. Is there a better way to do that?
Use initialLocation in GoRouter constructor. Something like this:
GoRouter(
initialLocation: '/page3',
routes: [
GoRoute(
path: '/',
builder: (context, state) => const Page1Screen(),
),
GoRoute(
path: '/page2',
builder: (context, state) => const Page2Screen(),
),
GoRoute(
path: '/page3',
builder: (context, state) => const Page3Screen(),
),
],
);

Flutter ways to switch between material apps or reload main function

I would like to have a clear separation of concerns between user enroll flow and the rest of the app. To do that I have created a MaterialApp for Enroll flow and a MaterialApp for the main application. When the user is done signing up - they should be directed to the main app. So something like this:
void main() async {
// ... init and stuff ... //
if(isUserAccountExists){
runApp(MultiProvider(
providers: [
Provider(create: (context) => DataStorage()),
ChangeNotifierProvider.value(value: settingsController),
ChangeNotifierProvider.value(value: oauthProvider),
ChangeNotifierProvider.value(value: deviceProvider),
ChangeNotifierProvider.value(value: messenger),
],
child: MainApp(settingsController: settingsController),
),);
} else runApp(EnrollApp());
}
My problem is when the user is done signing up, I have no ways to restart the application or reload the main() function. (I must restart due to initialization steps that precede the runApp call).
You can use flutter_phoenix to restart your application.
flutter_phoenix configuration:
dependencies:
flutter_phoenix: "^1.0.0"
import 'package:flutter_phoenix/flutter_phoenix.dart';
void main() {
runApp(
Phoenix(
child: App(),
),
);
}
Phoenix.rebirth(context);
You may follow these steps:
After your sign up, call Phoenix.rebirth(context); method to restart the application
In your splash screen or main widget check the database so that the user is already signed up or not then redirect the user to your ux/view.
You can extract your signup logic in separate Class(Widget) to handle which screen to render based on signup status. Something like here:
class _SeparationClassState extends State<SeparationClass> {
bool isUserAccountExists = false;
#override
Widget build(BuildContext context) {
// update isUserAccountExists to trigger rebuild
return Scaffold(
body: isUserAccountExists
? MultiProvider(
providers: [
Provider(create: (context) => DataStorage()),
ChangeNotifierProvider.value(value: settingsController),
ChangeNotifierProvider.value(value: oauthProvider),
ChangeNotifierProvider.value(value: deviceProvider),
ChangeNotifierProvider.value(value: messenger),
],
child: MainApp(settingsController: settingsController),
)
: EnrollApp(),
);
}
}
It doesn't needs to be a StatefulWidget, you can use Provider or Bloc pattern to handle signup logic and update your state (and ui) accordingly.

How can i do push replacement using go router plugin in flutter [go router]

I am using the go router plugin for my flutter web application, but I didn't find any way to do push replacement in navigation.
not only push replacement, can we do any other type of navigation link
pushNamedAndRemoveUntil
popUntil
because these navigation options must be needed in kind of any system!
What I tried
context.go(userStorage.redirectURL!);
GoRouter.of(context).go(PagesCollection.adminDashboard);
they only pushed the next page, not replacing
Note: I want this functionality in go router
Try this
Router.neglect(context, () {
context
.goNamed('third', params: {"id": ID});
});
It will neglect your current page. Hop this will helps you
I have had the same problem before. Then this way worked for me
First you need to avoid nested routes:
final GoRouter router = GoRouter(
routes: <GoRoute>[
GoRoute(
path: '/',
builder: (BuildContext context, GoRouterState state) =>
const OnboardingScreen(),
),
GoRoute(
path: '/login',
builder: (BuildContext context, GoRouterState state) => LoginScreen(),
),
GoRoute(
path: '/signup',
builder: (BuildContext context, GoRouterState state) =>
const SignupScreen(),
),
],
);
Use the above code instead of nesting like this:
final GoRouter router = GoRouter(
routes: <GoRoute>[
GoRoute(
routes: <GoRoute>[
GoRoute(
path: 'login',
builder: (BuildContext context, GoRouterState state) => LoginScreen(),
),
GoRoute(
path: '/signup',
builder: (BuildContext context, GoRouterState state) =>
const SignupScreen(),
),
],
path: '/',
builder: (BuildContext context, GoRouterState state) =>
const OnboardingScreen(),
),
],
);
This will make you able to replace OnboardingScreen() from the above eg. So next you can use pushreplacement future with:
context.go("/routname");
or
GoRouter.of(context).go("/routname");
If u don't want replacement, then can just use:
context.push("/routname");
or
GoRouter.of(context).push("/routname");
You can do it in a way ->
context.pop();
context.push(routeName);
Adding both these commands works similar to pushReplacement.
In the current version of go_router (5.1.10), you can use GoRouter.of(context).replace('/your-route) to do the same as Navigator.of(context).pushReplacement(yourPage).
There is a PR open to add popUntil but it looks like the flutter team doesn't want to support imperative routing methods and only focus on declarative routing (see, this issue).
It means the popUntil PR might never be merged, and pushNamedAndRemoveUntil never be supported.
It also means that push and replace might be removed in the future.
I am using go_router 6 and it works with:
context.pushReplacement()
What you can do is use Sub-Route Redirects in Go Router.
Let's consider you want users to first go on your Homepage and then from there they tap Login, and go to Login page and then after Logging in, they go to Dashboard Page.
But when they press Browser's Back Button they should go to Homepage and not the LoginPage i.e skipping the LoginPage just like "pushNameReplacement".
Then for this to happen you can configure redirects of each LoginPage and Dashboard page and get this functionality.
You can configure it such that whenever user (including from Browser's History) goes to Dashboard link it first checks if its Logged In then it opens otherwise it displays Login Page automatically.
Edited
i use this functions and they are useful for me
void popUntil(String name){
GoRouter router= AppRoutes.router;
String currentRoute=router.location;
while(router.canPop()&&name!=currentRoute){
currentRoute=router.location;
if(name!=currentRoute){
router.pop();
}
}
}
void pushNamedAndRemoveUntil(String name){
GoRouter router= AppRoutes.router;
while(router.canPop()){
router.pop();
}
router.replaceNamed(name);
}
work same as pushNamedAndRemoveUntil(route_name, (Route<dynamic> route) => false);
any suggestion please drop a comment

Problem with update multiprovider flutter

I recently updated some dependencies of my flutter application and I had this problem with the multiprovider, could someone guide me on how is the new syntax or what is the problem here?
the previous provider dependency I was working with was ^ 3.0.0 + 1, now it is at 5.0.0
Never post images of your code, we can't copy from it or reproduce it. Here's a setup of some multiproviders in a project I have:
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<UserState>(create: (ctx) => UserState()),
ChangeNotifierProvider<Cart>(create: (ctx) => Cart()),
ChangeNotifierProvider<LocationProvider>(create: (ctx) => LocationProvider()),
],
child: MaterialApp(theme: ThemeData(
primarySwatch: Colors.blue,
),home: Consumer<UserState>(builder: (context, userState, __) {
if (userState.firstRun) {
userState.getLastUser();
}
return userState.isSignedin ? CustomDrawer(appUser: userState.user) : LoginPageScreen();
}),
),
);
}
There are changes between provider ^3 and ^5, the documentation is pretty decent and does a good job explaining things. The code I posted is using provider: ^5.0.0.