我有一个快速的问题,为什么当async
存在时,我不能在onTap
中使用Navigator.push。删除async
和await
功能效果良好。Navigator.push按预期工作。但由于onTap内部有未来的函数调用,我无法导航到新类。
onTap: () async {
String _courierOrderID = await model.placeCourierOrder(widget.orderInfoMap);
// placeCourierOrder is just a Future<String> type function and it works fine. Order get placed successfully.
print("------- Courier Order Placed " + _courierOrderID.toString());
print("context: " + _courierOrderID.toString());
Navigator.push(context,
MaterialPageRoute(
builder: (context) => CourierOrderSummaryView(singleCourierDataID: _courierOrderID),
),
);
},
输出从下面的代码输出中,您可以看到我的订单成功下订单,但在Navigator.push
行,它给出了未处理的异常
------- Courier Order Placed 501-1c614
I/flutter (16526): context: LayoutBuilder(renderObject: _RenderLayoutBuilder#f6291 relayoutBoundary=up1 NEEDS-LAYOUT DETACHED)
E/flutter (16526): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
E/flutter (16526): At this point the state of the widget's element tree is no longer stable.
E/flutter (16526): To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.
E/flutter (16526): #0 Element._debugCheckStateIsActiveForAncestorLookup.<anonymous closure>
package:flutter/…/widgets/framework.dart:3864
E/flutter (16526): #1 Element._debugCheckStateIsActiveForAncestorLookup
package:flutter/…/widgets/framework.dart:3878
E/flutter (16526): #2 Element.findAncestorStateOfType
package:flutter/…/widgets/framework.dart:3926
E/flutter (16526): #3 Navigator.of
package:flutter/…/widgets/navigator.dart:2706
E/flutter (16526): #4 Navigator.push
package:flutter/…/widgets/navigator.dart:2116
E/flutter (16526): #5 _CourDelivReviewState.build.<anonymous closure>.<anonymous closure>.<anonymous closure>
package:storeifie/…/courierViews/courDelivReview.dart:560
E/flutter (16526): <asynchronous suspension>
E
也许这对你的有用
onTap: () async {
String _courierOrderID = await model.placeCourierOrder(widget.orderInfoMap);
await Navigator.push(context,
MaterialPageRoute(
builder: (context) => CourierOrderSummaryView(singleCourierDataID: _courierOrderID),
),
);
},
onTap: () async {
String _courierOrderID = await model.placeCourierOrder(widget.orderInfoMap);
// placeCourierOrder is just a Future<String> type function and it works fine. Order get placed successfully.
print("------- Courier Order Placed " + _courierOrderID.toString());
print("context: " + _courierOrderID.toString());
if(!mounted){
print('you are not in this context anymore");
// you changed the page and now you can't use this context.
}
Navigator.push(context,
MaterialPageRoute(
builder: (context) => CourierOrderSummaryView(singleCourierDataID: _courierOrderID),
),
);
},