how to refresh current page while doing pull to refresh (LiquidPullToRefresh) in Flutter Bloc - flutter

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
);

Related

couldn't create named routes in Flutter

I defined needed routes in Material App and everything works fine, bit I have to add another button which should lead to authorisation page and now I am getting this error:
The following assertion was thrown while handling a gesture:
Could not find a generator for route RouteSettings("/changeUsers", null) in the _WidgetsAppState.
Make sure your root app widget has provided a way to generate
this route.
Generators for routes are searched for in the following order:
1. For the "/" route, the "home" property, if non-null, is used.
2. Otherwise, the "routes" table is used, if it has an entry for the route.
3. Otherwise, onGenerateRoute is called. It should return a non-null value for any valid route not handled by "home" and "routes".
4. Finally if all else fails onUnknownRoute is called.
My code look like this:
return MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: '/',
routes: {
'/': (context) => const AuthorizationPage(),
'/adminLogin': (context) => const AuthInsertLogging(),
'/mainPageUsers': (context) => const TabBarBottomUsers(),
'/mainPageAdmin': (context) => const TabBarBottom(),
"/logout": (_) => new AuthorizationPage(),
'/changeUsers': (_) => AuthorizationPage(),
},
);
}
This is the button I tried to make route:
child: ElevatedButton(
onPressed: () {
Navigator.pushNamed(context, '/changeUsers');
},
child: Text(
'Change User',
style: GoogleFonts.montserrat(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w500,
letterSpacing: 2),
),
This is because you use the AuthorizationPage for '/' home, '/logout' and '/changeUsers' routes. There is a rule for routes property in Flutter documentation. See details here
If home is specified, then it implies an entry in this table for the
Navigator.defaultRouteName route ( here '/' ), and it is an error to
redundantly provide such a route in the routes table.
The rule says there must be only one home route ( here '/' route ) is specified. Here there are three routes pointing to same page.
So, just remove '/logout' and '/changeUers' routes and write onPressed function as follows.
Navigator.pushNamed(context, '/');

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).

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.