Flutter Go Router no back button and nothing to pop - flutter

I am using Go Router on my flutter project and I noticed that the back button is not presented anymore.
Even when I specifically add it I get the following error:
======== Exception caught by gesture ===============================================================
The following GoError was thrown while handling a gesture:
There is nothing to pop
When the exception was thrown, this was the stack:
#0 GoRouterDelegate.pop (package:go_router/src/delegate.dart:120:5)
#1 GoRouter.pop (package:go_router/src/router.dart:284:21)
#2 RecordDetailState.build. (package:random_me/screens/record/detail.dart:70:36)
#3 _InkResponseState.handleTap (package:flutter/src/material/ink_well.dart:1072:21)
#4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:253:24)
#5 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:627:11)
#6 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:306:5)
#7 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:239:7)
Widget build(BuildContext context) {
AppTranslations.init(context);
return Scaffold(
appBar: AppBar(
title: Text(TRANSLATION.record_detail),
leading: IconButton(
onPressed: () {
GoRouter.of(context).pop();
},
icon: Icon(Icons.arrow_back_ios),
//replace with our own icon data.
)),
Edit: If I call
GoRouter.of(context).push(CategoryDetail.routeName);
instead of
GoRouter.of(context).go(CategoryDetail.routeName);
it works;

Fixed: If I call
GoRouter.of(context).push(CategoryDetail.routeName);
instead of
GoRouter.of(context).go(CategoryDetail.routeName);
it works;

Related

The following _CastError was thrown building profile(dirty, state: _profileState#96d8f): Null check operator used on a null value

I dont't now why it through error while I pick image also the error happened .I have also checked this error by if else condition but it through same error .Please solve my error.Thanks in andvance
When I click on Button it throw this error
======== Exception caught by widgets library =======================================================
The following _CastError was thrown building profile(dirty, state: _profileState#96d8f):
Null check operator used on a null value
The relevant error-causing widget was:
profile profile:file:///D:/ecommerce/lib/Add_product/bottom_navigation.dart:31:5
When the exception was thrown, this was the stack:
#0 _profileState.build (package:ecommerce/Auth/profile.dart:54:123)
#1 StatefulElement.build (package:flutter/src/widgets/framework.dart:4992:27)
#2 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4878:15)
#3 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5050:11)
#4 Element.rebuild (package:flutter/src/widgets/framework.dart:4604:5)
#5 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2667:19)
#6 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:882:21)
#7 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:378:5)
#8 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1175:15)
#9 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1104:9)
#10 SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:881:7)
(elided 4 frames from class _RawReceivePortImpl, class _Timer, and dart:async-patch)
This is my code
ElevatedButton(onPressed: ()async{
storage.Reference reference=storage.FirebaseStorage.instance.ref("/images"+id);
storage.UploadTask task=reference.putFile(_image!.absolute);
await Future.value(task);
var geturl;
geturl=await reference.getDownloadURL();
final ref=FirebaseFirestore.instance.collection("Add_product");
ref.doc(id).set({"id":id,"product_name":namecontroller.text.toString(),"product_price":pricecontroller.text.toString(),"phonenumber":nocontroller.text.toString(),"url":geturl.toString()}).
then((value){
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("Product added",style: TextStyle(color: Colors.redAccent),
),duration: Duration(seconds: 5),
));
}).catchError((e){
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("${e.message}",style: TextStyle(color: Colors.redAccent),
),duration: Duration(seconds: 5),
));
});
Navigator.pop(context);
}, child: Text("Add Product",style: TextStyle(backgroundColor: Colors.blue,color: Colors.black),))
Based on error message it is comming from
storage.UploadTask task=reference.putFile(_image!.absolute); // this line using `!`
You can do a null check first and then move
ElevatedButton(onPressed: ()async{
storage.Reference reference=storage.FirebaseStorage.instance.ref("/images"+id);
if(_image==null){
log("got null on image");
return;
}
....

'Type 'Color' is not a subtype of 'MaterialColor' error appears every time I build my Flutter app on the simulator (Android and iOS) in Android Studio

I'm putting together a demo app, to help me learn various features of Flutter but at the moment, I am experiencing a recurring error I have not come across before.
Each time I build the app in Android Studio on any simulator (Android or iOS) an error is generated:
Type 'Color' is not a subtype of type 'MaterialColor'
Here is the exception and console output:
Launching lib/main.dart on iPhone 11 Pro Max in debug mode...
Running Xcode build...
Xcode build done. 16.9s
flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building MyApp(dirty):
flutter: type 'Color' is not a subtype of type 'MaterialColor'
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter: https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: The relevant error-causing widget was:
flutter: MyApp
flutter: file:///Users/JGolding/Desktop/Desktop/Work/App-and-Web-Development/App-Development/1-Demo-App/demo_app/lib/main.dart:4:23
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0 MyApp.build (package:demoapp/main.dart:13:35)
flutter: #1 StatelessElement.build (package:flutter/src/widgets/framework.dart:4291:28)
flutter: #2 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4223:15)
flutter: #3 Element.rebuild (package:flutter/src/widgets/framework.dart:3947:5)
flutter: #4 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4206:5)
flutter: #5 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4201:5)
flutter: #6 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3194:14)
flutter: #7 Element.updateChild (package:flutter/src/widgets/framework.dart:2988:12)
flutter: #8 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1028:16)
flutter: #9 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:999:5)
flutter: #10 RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:942:17)
flutter: #11 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2412:19)
flutter: #12 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:941:13)
flutter: #13 WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:819:7)
flutter: #14 WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:804:7)
flutter: #23 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:384:19)
flutter: #24 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:418:5)
flutter: #25 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)
flutter: (elided 8 frames from package dart:async and package dart:async-patch)
flutter:
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
Debug service listening on ws://127.0.0.1:60030/z8ejaMsnyI0=/ws
Syncing files to device iPhone 11 Pro Max...
This seems to suggest that the issue is in the main.dart file, which is here:
import 'package:demoapp/screens/home/home_page.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Demo App',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.blue[200],
),
home: HomePage(),
);
}
}
At the moment, in ThemeData() I am using primaryColor: Colors.blue[200]. For some reason, the app builds if I change that to primarySwatch: Colors.blue and then back again to primaryColor: Colors.blue[200]. This has never happened to me before and I'm not sure why it keeps happening on the first build of the app in the simulator. Why might this be happening? Is there a way to sort it?
I am using primaryColor since I want to use that specific shade of blue as the main color. If this is an issue with primaryColor, is there perhaps a way to use primarySwatch and be able to select the specific color in a family?
If you want to use custom color from hex like this color 0xFF0E7AC7
const MaterialColor kPrimaryColor = const MaterialColor(
0xFF0E7AC7,
const <int, Color>{
50: const Color(0xFF0E7AC7),
100: const Color(0xFF0E7AC7),
200: const Color(0xFF0E7AC7),
300: const Color(0xFF0E7AC7),
400: const Color(0xFF0E7AC7),
500: const Color(0xFF0E7AC7),
600: const Color(0xFF0E7AC7),
700: const Color(0xFF0E7AC7),
800: const Color(0xFF0E7AC7),
900: const Color(0xFF0E7AC7),
},
);
theme: ThemeData(
primarySwatch: kPrimaryColor,
),

Error "FormatException: Unexpected character (at character 1)" even in default default flutter web project

Whenever I create a new flutter web project, it gives me the same error: Unexpected Character (at character 1).
When I run webdev serve it gives a blank screen and stops.
and, on webdev daemon I get the error.
I made no changes in the code, and executed it as it was, that is, the default flutter web project.
I have uninstalled and reinstalled, tried flutter clean, but none of this is working:
Further details are given below:
Unhandled exception:
FormatException: Unexpected character (at character 1)
Not Found
^
#0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1392:5)
#1 _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1259:9)
#2 _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:924:22)
#3 _parseJson (dart:convert-patch/convert_patch.dart:29:10)
#4 JsonDecoder.convert (dart:convert/json.dart:493:36)
#5 JsonCodec.decode (dart:convert/json.dart:151:41)
#6 jsonDecode (dart:convert/json.dart:94:10)
#7 parse (package:source_maps/parser.dart:27:15)
#8 Sources.scriptParsed (package:dwds/src/debugging/sources.dart:62:19)
<asynchronous suspension>
#9 _RootZone.runUnaryGuarded (dart:async/zone.dart:1314:10)
#10 CastStreamSubscription._onData (dart:_internal/async_cast.dart:81:11)
#11 _RootZone.runUnaryGuarded (dart:async/zone.dart:1314:10)
#12 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336:11)
#13 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:263:7)
#14 _SinkTransformerStreamSubscription._add (dart:async/stream_transformers.dart:68:11)
#15 _EventSinkWrapper.add (dart:async/stream_transformers.dart:15:11)
#16 WipDomain.eventStream.<anonymous closure>.<anonymous closure> (package:webkit_inspection_protocol/webkit_inspection_protocol.dart:301:26)
#17 _HandlerEventSink.add (dart:async/stream_transformers.dart:228:7)
#18 _SinkTransformerStreamSubscription._handleData (dart:async/stream_transformers.dart:120:24)
#19 _RootZone.runUnaryGuarded (dart:async/zone.dart:1314:10)
#20 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336:11)
#21 _DelayedData.perform (dart:async/stream_impl.dart:591:14)
#22 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:707:11)
#23 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:667:7)
#24 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
#25 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
#26 _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:116:13)
#27 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:173:5)
pub failed (255)
My main.dart
import 'package:flutter_web/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
Widget build(BuildContext context) {
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (choose the "Toggle Debug Paint" action
// from the Flutter Inspector in Android Studio, or the "Toggle Debug
// Paint" command in Visual Studio Code) to see the wireframe for each
// widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Hello, World!',
),
],
),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
https://github.com/ipshitag/hello_world/tree/master/helloworld
This was a webdev bug on Windows that was fixed in webdev v2.5.0:
https://github.com/dart-lang/webdev/issues/514
https://github.com/dart-lang/webdev/pull/563
Run pub global activate webdev to update to the latest version.

Exception on OnPressed function while using animateTo function In TabbarView

I am Trying to write a code for my project which uses a TabBarView with 4 tabs and has a Global Key so that I can Use the Tab controller anywhere in the app,
however when I tried to Call the animateTo Function using an onpressed Function of Raised Button It Keeps Throwing Errors as follows:
Have Already Done This://Tried Creating a function in the same file as the controller to change the view
class MyTabsState extends State<MyTabs> with SingleTickerProviderStateMixin {
static final homePageKey=GlobalKey<MyTabsState>();
TabController tabcontroller;
#override
void initState() {
super.initState();
tabcontroller = new TabController(vsync: this, length: 4);
}
#override
void dispose() {
super.dispose();
tabcontroller.dispose();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
key: homePageKey,
bottomNavigationBar: new Material(
color: mainUiColor,
child: new TabBar(
controller: tabcontroller,
unselectedLabelColor: Colors.grey,
labelColor: Colors.redAccent,
tabs: <Tab>[
new Tab(icon: new Icon(Icons.home)),
new Tab(icon: new Icon(Icons.photo_album)),
new Tab(icon: new Icon(Icons.arrow_back)),
new Tab(icon: new Icon(Icons.favorite)),
])),
body: new TabBarView(controller: tabcontroller, children: <Widget>[
new First(),
new PhotoGallery(),
new Third(),
new SocialMedia(),
]),
);
}
void changePage(){
tabcontroller.animateTo(2);
}
}
I/flutter ( 4993): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════ I/flutter ( 4993): The following NoSuchMethodError was thrown while handling a gesture: I/flutter ( 4993): The method 'changePage' was called on null. I/flutter ( 4993): Receiver: null I/flutter ( 4993): Tried calling: changePage() I/flutter ( 4993): I/flutter ( 4993): When the exception was thrown, this was the stack: I/flutter ( 4993): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:50:5) I/flutter ( 4993): #1 _PhotoGalleryState.build.<anonymous closure> (package:myproject/screenTabs/SecondTab.dart:97:52) I/flutter ( 4993):
#2 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:511:14) I/flutter ( 4993):
#3 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:566:30) I/flutter ( 4993):
#4 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:166:24) I/flutter ( 4993): #5 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:240:9) I/flutter ( 4993): #6 TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:211:7) I/flutter ( 4993): #7 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27) I/flutter ( 4993): #8
_WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:225:20) I/flutter ( 4993):
#9 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:199:22) I/flutter ( 4993):
#10 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7) I/flutter ( 4993):
#11 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7) I/flutter ( 4993):
#12 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7) I/flutter ( 4993):
#16 _invoke1 (dart:ui/hooks.dart:233:10) I/flutter ( 4993): #17 _dispatchPointerDataPacket (dart:ui/hooks.dart:154:5) I/flutter ( 4993): (elided 3 frames from package dart:async) I/flutter ( 4993): I/flutter ( 4993): Handler: onTap I/flutter ( 4993): Recognizer: I/flutter ( 4993): TapGestureRecognizer#bfc40(debugOwner: GestureDetector, state: ready, won arena, finalPosition: I/flutter ( 4993): Offset(126.9, 667.6), sent tap down)
If I were a betting man I'd bet you may be trying to call changePage() on one of the pages listed in your tabBarView. A global key doesn't really make the item available anywhere in the app, you'd have to store it somewhere higher up in the widget tree using an inherited widget or pass it down to its children as a property in order to actually use it. It looks like something you may want to consider looking into is a CupertinoTabScaffold. Then you could wrap that around the main views, and work with it there and have it show up across the entire app. This might be a bit easier than using the current setup.

Cannot install a MaterialPageRoute<void> after disposing it

The setup
I have to simple routes, FirstRoute and SecondRoute. Each one contains a button to for the navigation. Pressing FirstRoute's button leads to second and vice-versa.
The exception
I am getting an exception when I am trying to navigate from FirstRoute to SecondRoute for the second time (first try is successful). Judging by the message "Cannot install a MaterialPageRoute after disposing it" I somehow disposed a route but I can't figure out which route and how I did that.
Here is the full error log:
══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter (26569): The following assertion was thrown while handling a gesture:
I/flutter (26569): Cannot install a MaterialPageRoute<void> after disposing it.
I/flutter (26569): 'package:flutter/src/widgets/routes.dart': Failed assertion: line 175 pos 12:
I/flutter (26569): '!_transitionCompleter.isCompleted'
I/flutter (26569): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter (26569): more information in this error message to help you determine and fix the underlying cause.
I/flutter (26569): In either case, please report this assertion by filing a bug on GitHub:
I/flutter (26569): https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter (26569): When the exception was thrown, this was the stack:
I/flutter (26569): #2 TransitionRoute.install (package:flutter/src/widgets/routes.dart:175:12)
I/flutter (26569): #3 ModalRoute.install (package:flutter/src/widgets/routes.dart:895:11)
I/flutter (26569): #4 NavigatorState.push (package:flutter/src/widgets/navigator.dart:1742:11)
I/flutter (26569): #5 Navigator.push (package:flutter/src/widgets/navigator.dart:1081:34)
I/flutter (26569): #6 _createOnPressed.<anonymous closure> (package:layout_tutorial/main.dart:46:32)
I/flutter (26569): #7 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:513:14)
I/flutter (26569): #8 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:568:30)
I/flutter (26569): #9 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:166:24)
I/flutter (26569): #10 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:246:9)
I/flutter (26569): #11 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7)
I/flutter (26569): #12 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:436:9)
I/flutter (26569): #13 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
I/flutter (26569): #14 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
I/flutter (26569): #15 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:214:19)
I/flutter (26569): #16 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:192:22)
I/flutter (26569): #17 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:149:7)
I/flutter (26569): #18 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
I/flutter (26569): #19 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
I/flutter (26569): #23 _invoke1 (dart:ui/hooks.dart:223:10)
I/flutter (26569): #24 _dispatchPointerDataPacket (dart:ui/hooks.dart:144:5)
I/flutter (26569): (elided 5 frames from class _AssertionError and package dart:async)
I/flutter (26569): Handler: onTap
I/flutter (26569): Recognizer:
I/flutter (26569): TapGestureRecognizer#1bc15(debugOwner: GestureDetector, state: possible, won arena, finalPosition:
I/flutter (26569): Offset(164.3, 365.3), sent tap down)
I/flutter (26569): ════════════════════════════════════════════════════════════════════════════════════════════════════
and here is the whole code in case someone wants to reproduce the error:
import 'package:flutter/material.dart';
typedef void OnPressed();
main() {
runApp(MaterialApp(
title: 'Navigation Basics',
home: FirstRoute(),
));
}
class FirstRoute extends StatelessWidget {
#override
Widget build(BuildContext context) {
return _getRouteScaffold('First route', 'Go to second route',
_createOnPressed(context, route: SecondRoute()));
}
}
class SecondRoute extends StatelessWidget {
#override
Widget build(BuildContext context) {
return _getRouteScaffold(
'Second route', 'Back to first route', _createOnPressed(context));
}
}
Widget _getRouteScaffold(String title, String buttonText, OnPressed function) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: RaisedButton(
child: Text(buttonText),
onPressed: function,
)),
);
}
OnPressed _createOnPressed(BuildContext context, {StatelessWidget route}) {
OnPressed function;
if (route != null) {
MaterialPageRoute<void> materialRoute =
MaterialPageRoute<void>(builder: (context) => route);
function = () => Navigator.push(context, materialRoute);
} else {
function = () => Navigator.pop(context);
}
return function;
}
All of those approaches are imho not best practices, but I am sure there was a reason to build this, the way it is built. Anyway I found the error in line 16:
_createOnPressed(context, route: SecondRoute()));
You pass this function to the button, which will always execute with the same SecondRoute. After a MaterialPageRoute has been disposed, it cannot be used anymore. Therefore you'll have to build a new route each time.
To do this you can simply warp your method call in another closure, which will then be executed on press, an initiate a new instance. I've simply adjusted line 16 to fix your error:
() => _createOnPressed(context, route: SecondRoute())());
Cheers :)