Navigator.push without animation - Flutter - flutter

I have several register forms with next buttons and I would like to switch between the different screens with
onTap: () => { Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SomeOtherScaffold()))
},
but without the default animation that comes with it.

If you want to use other animation, you can use transitionBuilder, in your PageRoute. How you can use this represented for you below:
import 'package:flutter/material.dart';
main() {
runApp(MaterialApp(
home: Page1(),
));
}
class Page1 extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: RaisedButton(
child: Text('Go!'),
onPressed: () {
Navigator.of(context).push(_createRoute());
},
),
),
);
}
}
Route _createRoute() {
return PageRouteBuilder(
pageBuilder: (context, animation, secondaryAnimation) => Page2(),
transitionsBuilder: (context, animation, secondaryAnimation, child) {
return child;
},
);
}
And if you want to transition instantly, you can do this:
transitionDuration: Duration(seconds: 0)
This will decrease down the transition time to 0 second, which will eventually results to quick transition speed.
To know more about Page Animation Transition follow these articles:
Page Route Animation
Everything you need for Flutter Page Transition
You need to define something for your transition, if you don't want the default one, and this answer will help you achieve this.

Related

How to use bloc initialised in one screen in a different screen

I have two screens in my flutter application Screen1 and Screen2. Screen1 is the home screen. I navigate from Screen1 to Screen2 via
Navigator.of(context).push(PageRouteBuilder<void>(pageBuilder: (context, animation, secondaryAnimation) => Screen2());
and Screen2 to Screen1 via
Navigator.pop(context);
Screen1 is statelesswidget:
class Screen1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<BlocA>(create: (_) => BlocA()),
BlocProvider<BlocB>(create: (_) => BlocB()),
]
child: RaisedButton(
child: Text('Goto Screen 2'),
onPressed: Navigator.of(context).push(PageRouteBuilder<void>(pageBuilder: (context, animation, secondaryAnimation) => Screen2());
),
)
}
}
I would appreciate anyone can provide an answer that will satisfy the following :
Want to access the two bloc initialised in the Screen1 from Screen2 using
BlocProvider.value(value: BlocProvider.of(context), child: ...)
without bringing the initialisation of blocs upto the MaterialApp widget. Cannot make the MultiBlocProvider the parent of MaterialApp. I want the blocs only accessed in Screen1 and Screen2. It should not be accessed by other screens.
Also when popped from Screen2 to Screen1, the blocs should not be disposed. Hence, continue to maintain state when popped from Screen2
Should not pass the bloc via constructor or as arguments in Navigator
Currently getting following error:
flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building Screen2(dirty):
flutter: BlocProvider.of() called with a context that does not contain a BlocA.
flutter: No ancestor could be found starting from the context that was passed to
flutter: BlocProvider.of<BlocA>().
flutter:
flutter: This can happen if the context you used comes from a widget above the BlocProvider.
flutter:
flutter: The context used was: Screen2(dirty)
The use the already created bloc instance on new page, you can use BlocProvider.value.
Like passing BlocX to next route will be like
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => BlocProvider.value(
value: BlocProvider.of<BlocX>(context),
child: Screen2(),
),
),
);
I might go for repository provider on your case. But to pass multiple instance, you can wrap BlocProvider two times on route.
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => BlocProvider.value(
value: BlocProvider.of<BlocA>(context),
child: BlocProvider.value(
value: BlocProvider.of<BlocB>(context),
child: Screen2(),
),
),
),
);
Currently, I cannot remember any better option, let me know if you've got any.
Now, your second route Screen2 can access both BlocB and BlocB instance.
You can get the instance it like, depend on your code structure.
BlocConsumer<BlocA, BlocAState>(
builder: (context, state) {
if (state is BlocAInitial) {
return Text(state.name);
}
return Text("un impleneted");
},
listener: (context, state) {},
),
When you create bloc, and like to pass it with BlocProvider.value(value: BlocProvider.of<BlocA>(context),, you need to use separate context.
More about blocprovider.
Check the demo, It will clarify, I am using Builder instead of creating new widget for context.
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Screen1(),
);
}
}
class Screen1 extends StatelessWidget {
const Screen1({super.key});
#override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<BlocA>(create: (_) => BlocA()),
BlocProvider<BlocB>(create: (_) => BlocB()),
],
child: Builder(builder: (context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => BlocProvider.value(
value: BlocProvider.of<BlocA>(context),
child: BlocProvider.value(
value: BlocProvider.of<BlocB>(context),
child: Screen2(),
),
),
),
);
},
),
);
}),
);
}
}
class Screen2 extends StatelessWidget {
const Screen2({super.key});
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
BlocConsumer<BlocA, BlocAState>(
builder: (context, state) {
if (state is BlocAInitial) {
return Text(state.name);
}
return Text("un impleneted");
},
listener: (context, state) {},
),
BlocConsumer<BlocB, BlocBState>(
builder: (context, state) {
if (state is BlocBInitial) {
return Text(state.name);
}
return Text("un impleneted");
},
listener: (context, state) {},
),
],
),
);
}
}
Find more about flutterbloccoreconcepts
you have to elevate MultiBlocProvider in the widget tree so that it wraps both screens, e.g. make it a parent of MaterialApp
You can pass bloc elements as a parameter to Screen2
final blocAObject = BlocProvider.of<BlocA>(context);
Navigator.of(context).push(PageRouteBuilder<void>(pageBuilder: (context, animation, secondaryAnimation) => Screen2(bloca:blocAObject));
If you're ok with initializing in MaterialApp while only having the blocs accessible from the two screens, try the following:
final blocA = BlocA(); // shared bloc instance
final blocB = BlocB(); // shared bloc instance
#override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
'screen1': (_) => MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => blocA,
),
BlocProvider(
create: (context) => blocB,
),
],
child: Screen1(),
),
'screen2': (_) => MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => blocA,
),
BlocProvider(
create: (context) => blocB,
),
],
child: Screen2(),
),
},
);
}

how to implement scoped model to navigation screen when scoped model initialized in the previous screen and not in myApp()

im trying to use scoped model in 2 screens in the app and i dont want to run the app with scoped model, i just initialize scoped model in first screen and it worked but i got an error in the second screen where i navigate to it. so what do i do?
first i call the first screen from the pre screen like this
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ServiceDetails(model: new CartModel()),
)
);
then in ServiceDetails i didnt get any error
so in build widget
#override
Widget build(BuildContext context) {
return ScopedModel(
model: widget.model,
child: Scaffold(...)
);
}
and i have a cart button which on tap:
onTap: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => new Cart()
),
);
},
Cart class:
class Cart extends StatefulWidget {
#override
_CartState createState() => _CartState();
}
class _CartState extends State<Cart> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Your Cart")),
body: ScopedModel.of<CartModel>(context, rebuildOnChange: true).cart.length == 0 ?
Container(
alignment: Alignment.center,
child: Text("Your cart is empty!",style: new TextStyle(color: Colors.grey))
) :
Container(
padding: EdgeInsets.only(top:15),
child: cartListView()
)
);
}
Widget cartListView(){
return ScopedModelDescendant<CartModel>(
builder: (context, child, model) {
return ListView.builder(
shrinkWrap: true,
itemCount: ScopedModel.of<CartModel>(context,rebuildOnChange: true).total,
itemBuilder: (context, index) {
return Container(
child: Image.asset(model.cart[index].fs.image)
)
}
)})}
}
so when i enter cart page i got an error
can't find the correct scoped model
anyone help plz

How to listen to previous screen Listener when navigate to a new Page?

I have a question about gestures.
I have a button that triggers to show a Dialog when long-press, choose the option when onMovePointer, and close the dialog when the user releases the pointer. Imagine it just like peek and drag to choose.
This is my code:
ElevatedButton(
onPressed: () {
Navigator.of(context).push(PageRouteBuilder(
pageBuilder: (context, animation,
secondaryAnimation) {
return IgnorePointer(
child: OnMoveDialog());
},
opaque: false));
},
child: Text('Show dialog'),
try to use GetX state management and instead of using listener use observation variables
for more info check this link
https://pub.dev/packages/get
if you want to insist on pure dart you have to use global listeners and notifier.
You can use Navigator API to return the modal result.
Refer to return data from a screen documentation
Documentation shows example with pages, but the same works for modal/dialog pages
Page Widget
In your case, on your ElevatedButton, wait for the Navigator response:
class _MyWidgetState extends State<MyWidget> {
/// ...
#override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
/// Wait for the result with `await Navigator...` and store it on a variable
final result = await Navigator.of(context).push<String>(
PageRouteBuilder(
pageBuilder: (context, animation, secondaryAnimation) {
return IgnorePointer(
child: OnMoveDialog(),
);
},
opaque: false,
),
);
if (result == 'option-1') { /* Handle option 1 */ }
if (result == 'option-2') { /* Handle option 2 */ }
},
child: Text('Show dialog'),
);
}
/// ...
}
Dialog Widget
In your modal widget, return the value when popping
class _MyModalState extends State<MyModalWidget> {
/// ...
#override
Widget build(BuildContext context) {
/// Pseudo Widget, is just to examplify your modal behavior
return MyModal(
children: [
Button(
'Option 1',
/// Here the magic happens, you need to pop the result
onTap: () => Navigator.pop<String>('option-1'),
),
Button(
'Option 2',
/// Same here, remeber: you can receive this callback as arguments
onTap: () => Navigator.pop<String>('option-2'),
),
],
);
}
/// ...
}

Navigator from MaterialApp builder

I'm trying to embed my whole App into an AppBar and a Footer.
So I tried giving a custom Builder to my MaterialApp which look like this (I replaced the footer and the app bar by a button for clarity)
import 'package:epicture/scenes/Landing.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My App',
initialRoute: '/',
builder: (context, child) => Container(
child: FlatButton(
child: Text('Click me'),
onPressed: () => Navigator.of(context).pushNamed('/app'),
)),
// In my current code
builder: (context, child) => Embedder(child),
routes: <String, WidgetBuilder>{
'/': (context) => Landing(),
'/app': (context) => Text('My App !'),
},
);
}
}
But on press of the 'Click me' button, an error is raised saying that the context doesn't have a Navigator
the context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget
But actually, the button is a footer that can be clicked to change page from every page.
I would like to know how to have access to the navigator from the custom builder and if I simply head toward the wrong way for having the same pattern in every page of my application (Footer + header)
You cannot access Navigator with context from inside the builder as any widget returned by this builder will be parent for the navigator.
So, what do I do? Can I access navigator here, how?
Yeah! You can, create a GlobalKey and pass it to your MaterialApp. Then use that key to access Navigator inside your builder.
Example:
import 'package:epicture/scenes/Landing.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final GlobalKey<NavigatorState> _navigator = GlobalKey<NavigatorState>();
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My App',
initialRoute: '/',
navigatorKey: _navigator,
builder: (context, child) {
return Container(
child: FlatButton(
child: Text('Click me'),
onPressed: () => _navigator.currentState.pushNamed('/app'),
),
);
},
routes: <String, WidgetBuilder>{
'/': (context) => Landing(),
'/app': (context) => Text('My App !'),
},
);
}
}
Hope that helps!
Rename this context variable to something else
builder: (context, child)
You are getting name clashs for the context you are using here:
onPressed: () => Navigator.of(context).pushNamed('/app'),

How to access Provided (Provider.of()) value inside showModalBottomSheet?

I have a FloatingActionButton inside a widget tree which has a BlocProvider from flutter_bloc. Something like this:
BlocProvider(
builder: (context) {
SomeBloc someBloc = SomeBloc();
someBloc.dispatch(SomeEvent());
return someBloc;
},
child: Scaffold(
body: ...
floatingActionButton: FloatingActionButton(
onPressed: _openFilterSchedule,
child: Icon(Icons.filter_list),
),
)
);
Which opens a modal bottom sheet:
void _openFilterSchedule() {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return TheBottomSheet();
},
);
}
I am trying to access SomeBloc using BlocProvider.of<SomeBloc>(context) inside TheBottomSheet but I get the following error:
BlocProvider.of() called with a context that does not contain a Bloc of type SomeBloc.
I have tried to use the solution described in https://stackoverflow.com/a/56533611/2457045 but only works for BottomSheet and not ModalBottomSheet.
Note: This is not restricted to BlocProvider or flutter_bloc. Any Provider from the provider package has the same behaviour.
How can I access BlocProvider.of<SomeBloc>(context) inside the showModalBottomSheet?
In case it's not possible to do that, how to adapt https://stackoverflow.com/a/56533611/2457045 solution to Modal Bottom Sheet?
InheritedWidgets, and therefore Providers, are scoped to the widget tree. They cannot be accessed outside of that tree.
The thing is, using showDialog and similar functions, the dialog is located in a different widget tree – which may not have access to the desired provider.
It is therefore necessary to add the desired providers in that new widget tree:
void myShowDialog() {
final myModel = Provider.of<MyModel>(context, listen: false);
showDialog(
context: context,
builder: (_) {
return Provider.value(value: myModel, child: SomeDialog());
},
);
}
Provider in showModalBottomSheet (Bottom-Sheet)
void myBottomSheet() {
final myModel = Provider.of<MyModel>(context, listen: false);
showModalBottomShee(
context: context,
builder: (_) {
return ListenableProvider.value(
value: myModel,
child: Text(myModel.txtValue),
);
},
);
}
You need move Provider to top layer(MaterialApp)
According to picture, Dialog widget is under MaterialApp, so this is why you using wrong context
wrap your whole child widget inside the consumer.
void myShowDialog() {
showDialog(
context: context,
builder: Consumer<MyModel>(
builder: (context, value, builder) {
retuen widget();
}
);
}
You should split Scaffold widget and its children, to another StatefulWidget
From single Widget
class MainScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return BlocProvider(
builder: (context) {
SomeBloc someBloc = SomeBloc();
someBloc.dispatch(SomeEvent());
return someBloc;
},
child: Scaffold(
body: ...
floatingActionButton: FloatingActionButton(
onPressed: _openFilterSchedule,
child: Icon(Icons.filter_list),
),
)
);
}
}
Splitted into these two widget
class MainScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return BlocProvider(
builder: (context) {
SomeBloc someBloc = SomeBloc();
someBloc.dispatch(SomeEvent());
return someBloc;
},
child: Screen(),
);
}
}
and ..
class Screen extends StatelessWidget {
void _openFilterSchedule() {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return TheBottomSheet();
},
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ...
floatingActionButton: FloatingActionButton(
onPressed: _openFilterSchedule,
child: Icon(Icons.filter_list),
),
);
}
}
I found a solution, Just return your showModalBottomSheet with a StatefulBuilder and use the context of your modalsheet builder to pass to your provider. a snippet of my code below:
Future<Widget> showModal(int qty, Product product) async {
return await showModalBottomSheet(
isScrollControlled: true,
backgroundColor: Colors.transparent,
context: context,
builder: (BuildContext ctx) {
return StatefulBuilder(builder: (ctx, state) {
return Container(
child: RaisedButton(
onPressed: () {
Product prod = Product(product.id,
product.sku, product.name, qty);
Provider.of<CartProvider>(ctx, listen:
false).addCart(prod);}),);
}
}
);
}
TLDR: Make sure your import statement's casings match your project's folder casings.
I came across one other quirk while debugging this same error. I had several providers that were all working, including in showModalBottomSheets, however one was not working. After combing through the entire widget tree, without finding any discrepancies, I found that I had capitalized the first letter of a folder on one of the import statements of my problem-child notifier. I think this confused the compiler and caused it to throw the Could not find the correct Provider above this widget error.
After ensuring the import statement casing matched the folder name, my provider problems were resolved. Hopefully this will save someone a headache.
Not finding a clear explanation of adding multiple provided values, I thought I'd share here for reference.
await showMobileModals(
isDismissible: false,
context: context,
child: MultiProvider(
providers: [
Provider.value(
value: provided_one,
),
Provider.value(
value: provided_two,
),
Provider.value(
value: provided_three,
),
],
child: Container(),
),
);
Faced the same issue while dealing with showModelBottomSheet, since it happens to work in a different (context)widget tree I had to level up my state to that of the app so that I could access my provider using the context.