问题
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()),
);
},
),
回答1:
- 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. ... });
来源:https://stackoverflow.com/questions/61988256/getting-exception-caught-by-widgets-library-failed-assertion-line-3289-pos-12