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.
Related
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).
So this is the scenario:
I build an app that the first route or the first thing to do is check with a API REST a verification of a token that I already have on localsorage. If the token is valid, proceed to the home page route, if don't we need to redirect them to login screen. All this is async. I already try to get this working adding a route like this:
Widget build(BuildContext context) {
return GetMaterialApp(
initialRoute: '/',
getPages: [
GetPage(
name: '/',
page: () => const AppPage(),
middlewares: [AppPageMiddleware()],
),
GetPage(name: '/login', page: () => const LoginPage()),
GetPage(
name: '/operator', page: () => const OperatorHomePage(), transition: Transition.zoom),
],
);
As you can see, I load a AppPage that the only thing that they do is show the loading spinner. The middleware called AppPageMiddleware uses this:
GetPageBuilder onPageBuildStart(GetPageBuilder? page) async {
// here I perform the call to the API and wait for the response.
// If the API response is true, I need to save the response
// and redirect to OperatorHomePage
print('Bindings of ${page.toString()} are ready');
return page!;
}
But I have an error here because I can't add async.
Maybe this is not the best way to do this, if you can suggest me another way, I will appreciate so much. Sorry, I'm new with GetX.
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.
am using bloc method for home screen. I want to do pull to refresh in home screen...
I tired too many ways not getting solution...could you please suggest some solution.
In side onrefresh() I added few changes
1 . BlocProvider(
create: (context) => OttGetAllMovie(httpClient: http.Client())
..add(FeedsFetched(widget.title, "homePage")),
//child: HomePage(),
child: OttGetHomeInnerCatPage(
wtitle: widget.title, mixpanelinner: widget.mixpanel),
)
2. _feedsBloc.add(FeedsFetched(widget.wtitle, "homePage"));
3. setState(() {
_feedsBloc.add(FeedsFetched(widget.wtitle, "homePage"));
BlocProvider(
create: (context) => OttGetAllMovie(httpClient: http.Client())
..add(FeedsFetched(widget.title, "homePage")),
//child: HomePage(),
child: OttGetHomeInnerCatPage(
wtitle: widget.title, mixpanelinner: widget.mixpanel),
)
});
While
this seems to be the method you're using to fetch data
OttGetAllMovie(httpClient: http.Client())
..add(FeedsFetched(widget.title, "homePage")),
Wrap your body in liquid pull to refresh
LiquidPullToRefresh(
key: _refreshIndicatorKey, // key if you want to add
onRefresh: ()async{
//cal your data source
OttGetAllMovie(httpClient: http.Client())
..add(FeedsFetched(widget.title, "homePage")),
}
child: ListView(), // scroll view
);
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.