Exception on OnPressed function while using animateTo function In TabbarView - flutter

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.

Related

Bad state no element in Flutter Using FutureBuilder and Provider

Using Provider and FutureBuilder, I just deleted data from database, it got removed at the same time, it shows a red screen with bad state no element. There is no problem to add data, do not show this problem.
Code is given below
stacktrace
ter (12519): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (12519): The following StateError was thrown building ViewNoteScreen(dirty, dependencies:
I/flutter (12519): [_ModalScopeStatus], state: _ViewNoteScreenState#f589b):
I/flutter (12519): Bad state: No element
I/flutter (12519):
I/flutter (12519): The relevant error-causing widget was:
I/flutter (12519): ViewNoteScreen file:///C:/Users/Admin/Desktop/daily%2010/provider_note/lib/main.dart:21:46
I/flutter (12519):
I/flutter (12519): When the exception was thrown, this was the stack:
I/flutter (12519): #0 ListMixin.firstWhere (dart:collection/list.dart:148:5)
I/flutter (12519): #1 Providers.findById (package:provider_note/helper/provider.dart:14:19)
I/flutter (12519): #2 _ViewNoteScreenState.build (package:provider_note/screens/view_note.dart:21:35)
I/flutter (12519): #3 StatefulElement.build (package:flutter/src/widgets/framework.dart:4663:28)
I/flutter (12519): #4 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4546:15)
I/flutter (12519): #5 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
I/flutter (12519): #6 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
I/flutter (12519): #7 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2667:33)
I/flutter (12519): #8 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:866:20)
I/flutter (12519): #9 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:286:5)
I/flutter (12519): #10 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1117:15)
I/flutter (12519): #11 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1056:9)
I/flutter (12519): #12 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:972:5)
I/flutter (12519): #16 _invoke (dart:ui/hooks.dart:253:10)
I/flutter (12519): #17 _drawFrame (dart:ui/hooks.dart:211:3)
I/flutter (12519): (elided 3 frames from dart:async)
I/flutter (12519):
I/flutter (12519): ══════════════════════════════════════════════
BadStateException occurred when list don't contain the item and still someone searching for that
Example:
If orElse not defined in the code and the wrong item gets search which doesn't exist in the list then it shows BadStateException
void main() {
List<String> list = ['red', 'yellow', 'pink', 'blue'];
var newList = list.firstWhere((element) => element.contains('green'));
print(newList);
}
Output:
Uncaught Error: Bad state: No element
Solution: Add orElse
void main() {
List<String> list = ['red', 'yellow', 'pink', 'blue'];
var newList = list.firstWhere((element) => element.contains(''),
orElse: () => 'No matching color found');
print(newList);
}
Output:
No matching color found
I think the easiest way for you is change your home to statefull widget and change this part of your code.
Navigator.pushNamed(
context, ViewNoteScreen.routeName,
arguments: notes.items[i].id).whenComplete(() {
setState(() {});
});

Getting EXCEPTION CAUGHT BY WIDGETS LIBRARY & Failed assertion: line 3289 pos 12: '!_debugLocked': is not true

From the code below, I would have the the widget _buildResultsWidget with a condition where it would move to a new state and from there when the new page is reached it would stay on for 2 seconds where is would returned me back but there would be an error appearing the moment the condition is activated.
import '../main.dart';
class DetectScreen extends StatefulWidget {
DetectScreen({Key key, this.title}) : super(key: key);
final String title;
#override
_DetectScreenPageState createState() => _DetectScreenPageState();
}
class _DetectScreenPageState extends State<DetectScreen>
with TickerProviderStateMixin {
AnimationController _colorAnimController;
Animation _colorTween;
bool open = false;
List<Result> outputs;
void initState() {
super.initState();
//Load TFLite Model
TFLiteHelper.loadModel().then((value) {
setState(() {
TFLiteHelper.modelLoaded = true;
});
});
//Initialize Camera
CameraHelper.initializeCamera();
//Setup Animation
_setupAnimation();
//Subscribe to TFLite's Classify events
TFLiteHelper.tfLiteResultsController.stream.listen((value) {
value.forEach((element) {
_colorAnimController.animateTo(element.confidence,
curve: Curves.bounceIn, duration: Duration(milliseconds: 500));
});
//Set Results
outputs = value;
//Update results on screen
setState(() {
//Set bit to false to allow detection again
CameraHelper.isDetecting = false;
});
}, onDone: () {
}, onError: (error) {
AppHelper.log("listen", error);
});
}
Widget _buildResultsWidget(double width, List<Result> outputs) {
open = true;
return Positioned.fill(
child: Align(
alignment: Alignment.bottomCenter,
child: Container(
height: 200.0,
width: width,
color: Colors.transparent,
child: outputs != null && outputs.isNotEmpty
? ListView.builder( // check ? if true or false
itemCount: outputs.length,
shrinkWrap: true,
padding: const EdgeInsets.all(20.0),
itemBuilder: (BuildContext context, int index) {
return Column(
children: <Widget>[
Text(
outputs[index].label,
style: TextStyle(
color: _colorTween.value,
fontSize: 20.0,
),
),
(outputs[index].label == "General Waste" && outputs[index].confidence > 0.1) == true ?
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => General(),
),
):
],
);
})
: Center(
child: Text("Wating for model to detect..",
style: TextStyle(
color: Colors.black,
fontSize: 20.0,
))),
),
),
);
}
}
void _setupAnimation() {
_colorAnimController =
AnimationController(vsync: this, duration: Duration(milliseconds: 5000));
_colorTween = ColorTween(begin: Colors.green, end: Colors.red)
.animate(_colorAnimController);
}
}
The condition where the moment it's activated, it would have the error
(outputs[index].label == "General Waste" && outputs[index].confidence > 0.1) == true ?
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => General(),
),
):
The code below where it's suppose to bring me to
class General extends StatefulWidget {
#override
_GeneralState createState() => new _GeneralState();
}
class _GeneralState extends State<General>
{
initState() {
super.initState();
new Timer(const Duration(seconds: 2), onClose); //Timer Here
}
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
backgroundColor: Colors.pink,
title: new Text("General Waste"),
),
);
}
void onClose() {
Navigator.pop(context);
}
And the error would happen the moment the condition is activated
Installing build\app\outputs\apk\app.apk...
I/flutter ( 803): {loadModel} {Loading model..}
I/flutter ( 803): {_initializeCamera} {Initializing camera..}
I/flutter ( 803): {_initializeCamera} {Camera initialized, starting camera stream..}
I/flutter ( 803): {classifyImage} {Results loaded. 1}
I/flutter ( 803): {classifyImage} {0.7169606685638428 , 3, General Waste}
I/flutter ( 803): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 803): The following assertion was thrown building:
I/flutter ( 803): setState() or markNeedsBuild() called during build.
I/flutter ( 803): This Overlay widget cannot be marked as needing to build because the framework is already in the
I/flutter ( 803): process of building widgets. A widget can be marked as needing to be built during the build phase
I/flutter ( 803): only if one of its ancestors is currently building. This exception is allowed because the framework
I/flutter ( 803): builds parent widgets before children, which means a dirty descendant will always be built.
I/flutter ( 803): Otherwise, the framework might not visit this widget during this build phase.
I/flutter ( 803): The widget on which setState() or markNeedsBuild() was called was:
I/flutter ( 803): Overlay-[LabeledGlobalKey<OverlayState>#8b7b3]
I/flutter ( 803): The widget which was currently being built when the offending call was made was:
I/flutter ( 803): SliverList
I/flutter ( 803):
I/flutter ( 803): When the exception was thrown, this was the stack:
I/flutter ( 803): #0 Element.markNeedsBuild.<anonymous closure> (package:flutter/src/widgets/framework.dart:4167:11)
I/flutter ( 803): #1 Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:4182:6)
I/flutter ( 803): #2 State.setState (package:flutter/src/widgets/framework.dart:1253:14)
I/flutter ( 803): #3 OverlayState.rearrange (package:flutter/src/widgets/overlay.dart:415:5)
I/flutter ( 803): #4 NavigatorState._flushHistoryUpdates (package:flutter/src/widgets/navigator.dart:3069:16)
I/flutter ( 803): #5 NavigatorState.push (package:flutter/src/widgets/navigator.dart:3297:5)
I/flutter ( 803): #6 _DetectScreenPageState._buildResultsWidget.<anonymous closure> (package:prototypestart/screens/detect_screen.dart:203:43)
I/flutter ( 803): #7 SliverChildBuilderDelegate.build (package:flutter/src/widgets/sliver.dart:446:22)
I/flutter ( 803): #8 SliverMultiBoxAdaptorElement._build.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1134:67)
I/flutter ( 803): #9 _HashMap.putIfAbsent (dart:collection-patch/collection_patch.dart:139:29)
I/flutter ( 803): #10 SliverMultiBoxAdaptorElement._build (package:flutter/src/widgets/sliver.dart:1134:26)
I/flutter ( 803): #11 SliverMultiBoxAdaptorElement.createChild.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1147:55)
I/flutter ( 803): #12 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2607:19)
I/flutter ( 803): #13 SliverMultiBoxAdaptorElement.createChild (package:flutter/src/widgets/sliver.dart:1140:11)
I/flutter ( 803): #14 RenderSliverMultiBoxAdaptor._createOrObtainChild.<anonymous closure> (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:354:23)
I/flutter ( 803): #15 RenderObject.invokeLayoutCallback.<anonymous closure> (package:flutter/src/rendering/object.dart:1866:58)
I/flutter ( 803): #16 PipelineOwner._enableMutationsToDirtySubtrees (package:flutter/src/rendering/object.dart:918:15)
I/flutter ( 803): #17 RenderObject.invokeLayoutCallback (package:flutter/src/rendering/object.dart:1866:13)
I/flutter ( 803): #18 RenderSliverMultiBoxAdaptor._createOrObtainChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:343:5)
I/flutter ( 803): #19 RenderSliverMultiBoxAdaptor.addInitialChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:427:5)
I/flutter ( 803): #20 RenderSliverList.performLayout (package:flutter/src/rendering/sliver_list.dart:79:12)
I/flutter ( 803): #21 RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
I/flutter ( 803): #22 RenderSliverEdgeInsetsPadding.performLayout (package:flutter/src/rendering/sliver_padding.dart:135:11)
I/flutter ( 803): #23 RenderSliverPadding.performLayout (package:flutter/src/rendering/sliver_padding.dart:375:11)
I/flutter ( 803): #24 RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
I/flutter ( 803): #25 RenderViewportBase.layoutChildSequence (package:flutter/src/rendering/viewport.dart:452:13)
I/flutter ( 803): #26 RenderShrinkWrappingViewport._attemptLayout (package:flutter/src/rendering/viewport.dart:1783:12)
I/flutter ( 803): #27 RenderShrinkWrappingViewport.performLayout (package:flutter/src/rendering/viewport.dart:1741:20)
I/flutter ( 803): #28 RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
I/flutter ( 803): #29 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
I/flutter ( 803): #30 RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
I/flutter ( 803): #31 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
I/flutter ( 803): #32 RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
I/flutter ( 803): #33 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
I/flutter ( 803): #34 RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
I/flutter ( 803): #35 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
I/flutter ( 803): #36 RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
I/flutter ( 803): #37 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
I/flutter ( 803): #38 RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
I/flutter ( 803): #39 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
I/flutter ( 803): #40 RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
I/flutter ( 803): #41 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
I/flutter ( 803): #42 RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
I/flutter ( 803): #43 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
I/flutter ( 803): #44 RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
I/flutter ( 803): #45 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
I/flutter ( 803): #46 RenderObject.layout (package:flutter/src/rendering/object.dart:1767:7)
I/flutter ( 803): #47 RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:111:13)
I/flutter ( 803): #48 RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1630:7)
I/flutter ( 803): #49 PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:887:18)
I/flutter ( 803): #50 RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:402:19)
I/flutter ( 803): #51 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:884:13)
I/flutter ( 803): #52 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:284:5)
I/flutter ( 803): #53 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1113:15)
I/flutter ( 803): #54 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1052:9)
I/flutter ( 803): #55 SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:968:5)
I/flutter ( 803): #59 _invoke (dart:ui/hooks.dart:261:10)
I/flutter ( 803): #60 _drawFrame (dart:ui/hooks.dart:219:3)
I/flutter ( 803): (elided 3 frames from dart:async)
I/flutter ( 803): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter ( 803): {classifyImage} {Results loaded. 1}
I/flutter ( 803): {classifyImage} {0.754631757736206 , 3, General Waste}
E/flutter ( 803): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: 'package:flutter/src/widgets/navigator.dart': Failed assertion: line 2334 pos 18: '!navigator._debugLocked': is not true.
E/flutter ( 803): #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39)
E/flutter ( 803): #1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5)
E/flutter ( 803): #2 _RouteEntry.handlePush.<anonymous closure> (package:flutter/src/widgets/navigator.dart:2334:18)
E/flutter ( 803): #3 TickerFuture.whenCompleteOrCancel.thunk (package:flutter/src/scheduler/ticker.dart:398:15)
E/flutter ( 803): #4 _rootRunUnary (dart:async/zone.dart:1192:38)
E/flutter ( 803): #5 _CustomZone.runUnary (dart:async/zone.dart:1085:19)
E/flutter ( 803): #6 _FutureListener.handleValue (dart:async/future_impl.dart:141:18)
E/flutter ( 803): #7 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:682:45)
E/flutter ( 803): #8 Future._propagateToListeners (dart:async/future_impl.dart:711:32)
E/flutter ( 803): #9 Future._completeWithValue (dart:async/future_impl.dart:526:5)
E/flutter ( 803): #10 Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:556:7)
E/flutter ( 803): #11 _rootRun (dart:async/zone.dart:1184:13)
E/flutter ( 803): #12 _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter ( 803): #13 _CustomZone.runGuarded (dart:async/zone.dart:979:7)
E/flutter ( 803): #14 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1019:23)
E/flutter ( 803): #15 _microtaskLoop (dart:async/schedule_microtask.dart:43:21)
E/flutter ( 803): #16 _startMicrotaskLoop (dart:async/schedule_microtask.dart:52:5)
E/flutter ( 803):
I/flutter ( 803): Another exception was thrown: 'package:flutter/src/widgets/navigator.dart': Failed assertion: line 3289 pos 12: '!_debugLocked': is not true.
I/flutter ( 803): {classifyImage} {Results loaded. 1}
I/flutter ( 803): {classifyImage} {0.7490702271461487 , 3, General Waste}
I/flutter ( 803): Another exception was thrown: 'package:flutter/src/widgets/navigator.dart': Failed assertion: line 3289 pos 12: '!_debugLocked': is not true.
E/flutter ( 803): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: 'package:flutter/src/widgets/navigator.dart': Failed assertion: line 3289 pos 12: '!_debugLocked': is not true.
E/flutter ( 803): #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:42:39)
E/flutter ( 803): #1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:38:5)
E/flutter ( 803): #2 NavigatorState.push (package:flutter/src/widgets/navigator.dart:3289:12)
E/flutter ( 803): #3 Navigator.push (package:flutter/src/widgets/navigator.dart:1737:34)
E/flutter ( 803): #4 _GeneralState.onClose (package:prototypestart/screens/information.dart:31:15)
E/flutter ( 803): #5 _rootRun (dart:async/zone.dart:1180:38)
E/flutter ( 803): #6 _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter ( 803): #7 _CustomZone.runGuarded (dart:async/zone.dart:979:7)
E/flutter ( 803): #8 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1019:23)
E/flutter ( 803): #9 _rootRun (dart:async/zone.dart:1184:13)
E/flutter ( 803): #10 _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter ( 803): #11 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1003:23)
E/flutter ( 803): #12 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:23:15)
E/flutter ( 803): #13 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter ( 803): #14 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter ( 803): #15 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter ( 803):
But using RaisedButton works just fine
RaisedButton(
child: Text('General Waste'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => General()),
);
},
),
This becomes quite simple - there's two ways to do this. The simple way is to
just use a delayed future with zero delay,
which will have dart schedule the call as soon as possible once the current
call stack returns to the event loop:
Future.delayed(Duration.zero, () {
Navigator. ...
});

Flutter: navigate to another screen from inside of StreamBuilder builder callback

I have a splash screen and a StreamBuilder that emits a state that contains information about authentication status. When the authentication status is known, I want to navigate either to sign in page or home page. But when I write something like Navigator.of(context).pushReplacement(...) I get
I/flutter ( 2058): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 2058): The following assertion was thrown building StreamBuilder(dirty, state:
I/flutter ( 2058): _StreamBuilderBaseState>#f4346):
I/flutter ( 2058): setState() or markNeedsBuild() called during build.
I/flutter ( 2058): This Overlay widget cannot be marked as needing to build because the framework is already in the
I/flutter ( 2058): process of building widgets. A widget can be marked as needing to be built during the build phase
I/flutter ( 2058): only if one of its ancestors is currently building. This exception is allowed because the framework
I/flutter ( 2058): builds parent widgets before children, which means a dirty descendant will always be built.
I/flutter ( 2058): Otherwise, the framework might not visit this widget during this build phase.
I/flutter ( 2058): The widget on which setState() or markNeedsBuild() was called was:
I/flutter ( 2058): Overlay-[LabeledGlobalKey#e0460](state: OverlayState#ab1a5(entries:
I/flutter ( 2058): [OverlayEntry#4e962(opaque: false; maintainState: false), OverlayEntry#7656a(opaque: false;
I/flutter ( 2058): maintainState: true), OverlayEntry#1f86e(opaque: false; maintainState: false),
I/flutter ( 2058): OverlayEntry#05a15(opaque: false; maintainState: true)]))
I/flutter ( 2058): The widget which was currently being built when the offending call was made was:
I/flutter ( 2058): StreamBuilder(dirty, state: _StreamBuilderBaseState>#f4346)
I/flutter ( 2058):
I/flutter ( 2058): When the exception was thrown, this was the stack:
I/flutter ( 2058): #0 Element.markNeedsBuild. (package:flutter/src/widgets/framework.dart:3503:11)
I/flutter ( 2058): #1 Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:3529:6)
I/flutter ( 2058): #2 State.setState (package:flutter/src/widgets/framework.dart:1133:14)
I/flutter ( 2058): #3 OverlayState.insertAll (package:flutter/src/widgets/overlay.dart:346:5)
I/flutter ( 2058): #4 OverlayRoute.install (package:flutter/src/widgets/routes.dart:43:24)
I/flutter ( 2058): #5 TransitionRoute.install (package:flutter/src/widgets/routes.dart:180:11)
I/flutter ( 2058): #6 ModalRoute.install (package:flutter/src/widgets/routes.dart:895:11)
I/flutter ( 2058): #7 NavigatorState.pushReplacement (package:flutter/src/widgets/navigator.dart:1799:14)
I/flutter ( 2058): #8 _replace (package:map_chat/application/navigation.dart:75:27)
I/flutter ( 2058): #9 _SignInPage.replace (package:map_chat/application/navigation.dart:67:5)
I/flutter ( 2058): #10 Roadmap.replace (package:map_chat/application/navigation.dart:25:18)
I/flutter ( 2058): #11 _SplashPageState._buildPageBasedOnAuthenticationState (package:map_chat/feature/splash.dart:52:19)
I/flutter ( 2058): #12 _SplashPageState._buildSplashScreen (package:map_chat/feature/splash.dart:40:11)
I/flutter ( 2058): #13 _SplashPageState._buildPage. (package:map_chat/feature/splash.dart:27:18)
I/flutter ( 2058): #14 StreamBuilder.build (package:flutter/src/widgets/async.dart:425:74)
I/flutter ( 2058): #15 _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:125:48)
I/flutter ( 2058): #16 StatefulElement.build (package:flutter/src/widgets/framework.dart:3825:27)
I/flutter ( 2058): #17 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3739:15)
I/flutter ( 2058): #18 Element.rebuild (package:flutter/src/widgets/framework.dart:3565:5)
I/flutter ( 2058): #19 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2278:33)
I/flutter ( 2058): #20 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:700:20)
I/flutter ( 2058): #21 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:286:5)
I/flutter ( 2058): #22 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1012:15)
I/flutter ( 2058): #23 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:952:9)
I/flutter ( 2058): #24 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.scheduleWarmUpFrame. (package:flutter/src/scheduler/binding.dart:773:7)
I/flutter ( 2058): #33 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:382:19)
I/flutter ( 2058): #34 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:416:5)
I/flutter ( 2058): #35 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)
I/flutter ( 2058): (elided 8 frames from package dart:async and package dart:async-patch)
The only workaround I found is to schedule the navigation to the end of event queue using Future(...).then(navigate) but that's sick. Is here an adequate solution for this?
You can listen your stream outside of build method and redirect to another view from there.
---- EDITED ----
This is an example of how you can do that:
#override
void initState() {
super.initState();
Future.delayed(Duration.zero, _verify);
}
void _verify() {
final _myBloc = BlocProvider.getBloc<MyBloc>();
_myBloc.myStream.listen((data) {
// Redirect to another view, given your condition
if (data) {
Navigator.of(context).pushNamed("my-new-route");
}
});
}
Just remember to save the StreamSubscription object returned from listen method, so you can cancel the subscription on dispose().
I still not happy with my solution, but I use a
if(snapshot.hasdata && snapshot.data.navigate) {
Future.microtask(() => Navigator.of(context).push... );
}

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

Flutter Googlemaps error when opening new route

I have BottomNavigationBar using IndexedStack so that my googleMaps wont reload when changing page. In page one I have a button and on page two I have googleMaps. When I push the button I want the page to change to page two and then to call function in there. For example to zoom to new location.
I'm using scoped model to handle my state.
I have already figured out a way to change the page, but I'm not sure what to do with the GoogleMapsController. I lifted it to ScopedModel class, but now I'm getting error when opening new route and closing it and then trying to change push the button to go to a location on the map:
I/flutter ( 8784): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter ( 8784): The following NoSuchMethodError was thrown while handling a gesture:
I/flutter ( 8784): The method 'animateCamera' was called on null.
I/flutter ( 8784): Receiver: null
I/flutter ( 8784): Tried calling: animateCamera(Instance of 'CameraUpdate')
I/flutter ( 8784):
I/flutter ( 8784): When the exception was thrown, this was the stack:
I/flutter ( 8784): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
I/flutter ( 8784): #1 AppStateModel.goToMapLocation
package:restapoints/state/app_state.dart:57
I/flutter ( 8784): #2 RestaurantInfoPageState.build.<anonymous closure>.<anonymous closure>
package:restapoints/pages/restaurant_page.dart:56
I/flutter ( 8784): #3 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:507
I/flutter ( 8784): #4 _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:562
I/flutter ( 8784): #5 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:102
I/flutter ( 8784): #6 TapGestureRecognizer._checkUp
package:flutter/…/gestures/tap.dart:242
I/flutter ( 8784): #7 TapGestureRecognizer.acceptGesture
package:flutter/…/gestures/tap.dart:204
I/flutter ( 8784): #8 GestureArenaManager.sweep
package:flutter/…/gestures/arena.dart:156
I/flutter ( 8784): #9 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent
package:flutter/…/gestures/binding.dart:184
I/flutter ( 8784): #10 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent
package:flutter/…/gestures/binding.dart:158
I/flutter ( 8784): #11 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent
package:flutter/…/gestures/binding.dart:138
I/flutter ( 8784): #12 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue
package:flutter/…/gestures/binding.dart:101
I/flutter ( 8784): #13 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket
package:flutter/…/gestures/binding.dart:85
I/flutter ( 8784): #14 _invoke1 (dart:ui/hooks.dart:168:13)
I/flutter ( 8784): #15 _dispatchPointerDataPacket (dart:ui/hooks.dart:122:5)
I/flutter ( 8784):
I/flutter ( 8784): Handler: onTap
I/flutter ( 8784): Recognizer:
I/flutter ( 8784): TapGestureRecognizer#5de3a(debugOwner: GestureDetector, state: ready, won arena, finalPosition:
I/flutter ( 8784): Offset(320.8, 298.5), sent tap down)
I/flutter ( 8784): ════════════════════════════════════════════════════════════════════════════════════════════════════
Thank you!
read about initState()
This is the first method called when the widget is created, it must be StatefullWidget
#override
void initState() {
// You can call your zooom to new location function here
super.initState();
}
This error was resolved by moving the ScopedModel to the top of Widget tree:
AppStateModel model = AppStateModel();
runApp(
ScopedModel<AppStateModel>(
model: model,
child: MaterialApp(
home: HomeWidget(),
),
),
);
So for anybody having trouble with googlemaps reloading in tabNav, use Indexed stack and wrap all the pages to Navigator. Then lift GooglemapsController to ScopedModel and put the ScopedModel(or any other state management model) to the root of your application.