我在使用flutter里的对话框控件的时候遇到了一个奇怪的错误

Another exception was thrown: Navigator operation requested with a context that does not include a Navigator

研究了一下才知道,flutter里的dialog不是随便就能用的。

原代码如下:

import 'package:flutter/material.dart';

main() {
runApp(new MyApp());
} class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Test',
home: new Scaffold(
appBar: new AppBar(title: new Text('Test')),
body: _buildCenterButton(context),
),
);
}
} Widget _buildCenterButton(BuildContext context) {
return new Container(
alignment: Alignment.center,
child: new Container(
child: _buildButton(context),
));
} Widget _buildButton(BuildContext context) {
return new RaisedButton(
padding: new EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 10.0),
//padding
child: new Text(
'show dialog',
style: new TextStyle(
fontSize: 18.0, //textsize
color: Colors.white, // textcolor
),
),
color: Theme.of(context).accentColor,
elevation: 4.0,
//shadow
splashColor: Colors.blueGrey,
onPressed: () {
showAlertDialog(context);
});
}
void showAlertDialog(BuildContext context) {
showDialog(
context: context,
builder: (_) => new AlertDialog(
title: new Text("Dialog Title"),
content: new Text("This is my content"),
actions:<Widget>[
new FlatButton(child:new Text("CANCEL"), onPressed: (){
Navigator.of(context).pop(); },),
new FlatButton(child:new Text("OK"), onPressed: (){
Navigator.of(context).pop(); },)
] ));
}

点击按钮的时候没有任何反应,控制台的报错是:

Another exception was thrown: Navigator operation requested with a context that does not include a Navigator

分析下源码吧~

看showDialog方法的源码:

Future<T> showDialog<T>({
@required BuildContext context,
bool barrierDismissible: true,
@Deprecated(
'Instead of using the "child" argument, return the child from a closure '
'provided to the "builder" argument. This will ensure that the BuildContext '
'is appropriate for widgets built in the dialog.'
) Widget child,
WidgetBuilder builder,
}) {
assert(child == null || builder == null);
return Navigator.of(context, rootNavigator: true/*注意这里*/).push(new _DialogRoute<T>(
child: child ?? new Builder(builder: builder),
theme: Theme.of(context, shadowThemeOnly: true),
barrierDismissible: barrierDismissible,
barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
));
}

Navigator.of 的源码:

static NavigatorState of(
BuildContext context, {
bool rootNavigator: false,
bool nullOk: false,
}) {
final NavigatorState navigator = rootNavigator
? context.rootAncestorStateOfType(const TypeMatcher<NavigatorState>())
: context.ancestorStateOfType(const TypeMatcher<NavigatorState>());
assert(() {
if (navigator == null && !nullOk) {
throw new FlutterError(
'Navigator operation requested with a context that does not include a Navigator.\n'
'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.'
);
}
return true;
}());
return navigator;
}

找到了一模一样的错误信息字符串!看来就是因为Navigator.of(context)抛出了一个FlutterError。
之所以出现这个错误,是因为满足了if (navigator == null && !nullOk) 的条件, 也就是说:
context.rootAncestorStateOfType(const TypeMatcher<NavigatorState>()) 是null。

Navigator.of函数有3个参数,第一个是BuildContext,第二个是rootNavigator,默认为false,可不传,第三个是nullOk,默认为false,可不传。rootNavigator的值决定了是调用ancestorStateOfType还是rootAncestorStateOfType,nullOk的值决定了如果最终结果为null值时该抛出异常还是直接返回一个null。

我们做个测试,传入不同的rootNavigator和nullOk的值,看有什么结果:

void showAlertDialog(BuildContext context) {
try{
debugPrint("Navigator.of(context, rootNavigator=true, nullOk=false)="+
(Navigator.of(context, rootNavigator: true, nullOk: false)).toString());
}catch(e){
debugPrint("error1 " +e.toString());
}
try{
debugPrint("Navigator.of(context, rootNavigator=false, nullOk=false)="+
(Navigator.of(context, rootNavigator: false, nullOk: false)).toString());
}catch(e){
debugPrint("error2 " +e.toString());
}
try{
debugPrint("Navigator.of(context, rootNavigator=false, nullOk=true)="+
(Navigator.of(context, rootNavigator: false, nullOk: true)).toString());
}catch(e){
debugPrint("error3 " +e.toString());
}
//先注释掉showDialog部分的代码
// showDialog(
// context: context,
// builder: (_) => new AlertDialog(
// title: new Text("Dialog Title"),
// content: new Text("This is my content"),
// actions:<Widget>[
// new FlatButton(child:new Text("CANCEL"), onPressed: (){
// Navigator.of(context).pop();
//
// },),
// new FlatButton(child:new Text("OK"), onPressed: (){
// Navigator.of(context).pop();
//
// },)
// ]
//
// ));
}

打印结果:

error1 Navigator operation requested with a context that does not include a Navigator.
error2 Navigator operation requested with a context that does not include a Navigator.
Navigator.of(context, rootNavigator=false, nullOk=true)=null

显然,无论怎么改rootNavigator和nullOk的值,Navigator.of(context, rootNavigator, nullOk)的值都是null。

为什么呢?

rootAncestorStateOfType函数的实现位于framework.dart里,我们可以看一下ancestorStateOfTyperootAncestorStateOfType的区别:

@override
State ancestorStateOfType(TypeMatcher matcher) {
assert(_debugCheckStateIsActiveForAncestorLookup());
Element ancestor = _parent;
while (ancestor != null) {
if (ancestor is StatefulElement && matcher.check(ancestor.state))
break;
ancestor = ancestor._parent;
}
final StatefulElement statefulAncestor = ancestor;
return statefulAncestor?.state;
} @override
State rootAncestorStateOfType(TypeMatcher matcher) {
assert(_debugCheckStateIsActiveForAncestorLookup());
Element ancestor = _parent;
StatefulElement statefulAncestor;
while (ancestor != null) {
if (ancestor is StatefulElement && matcher.check(ancestor.state))
statefulAncestor = ancestor;
ancestor = ancestor._parent;
}
return statefulAncestor?.state;
}

可以看出:
ancestorStateOfType的作用是: 如果某个父元素满足一定条件, 则返回这个父节点的state属性;
rootAncestorStateOfType的作用是: 返回最顶层的满足一定条件的父元素。
这个条件是: 这个元素必须属于StatefulElement , 而且其state属性与参数里的TypeMatcher 相符合。

查询源码可以知道:StatelessWidget 里的元素是StatelessElement,StatefulWidget里的元素是StatefulElement。

也就是说,要想让context.rootAncestorStateOfType(const TypeMatcher<NavigatorState>())的返回值不为null, 必须保证context所在的Widget的顶层Widget属于StatefulWidget(注意是顶层Widget,而不是自己所在的widget。如果context所在的Widget就是顶层Widget,也是不可以的)。

这样我们就大概知道为什么会出错了。我们的showAlertDialog方法所用的context是属于MyApp的, 而MyApp是个StatelessWidget。

那么,修改方案就比较清晰了,我们的对话框所使用的context不能是顶层Widget的context,同时顶层Widget必须是StatefulWidget。

修改后的完整代码如下:

import 'package:flutter/material.dart';

main() {
runApp(new MyApp());
} class MyApp extends StatefulWidget { @override
State<StatefulWidget> createState() {
return new MyState();
}
}
class MyState extends State<MyApp>{
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Test',
home: new Scaffold(
appBar: new AppBar(title: new Text('Test')),
body: new StatelessWidgetTest(),
),
);
} }
class StatelessWidgetTest extends StatelessWidget {
@override
Widget build(BuildContext context) {
return _buildCenterButton(context);
}
}
Widget _buildCenterButton(BuildContext context) {
return new Container(
alignment: Alignment.center,
child: new Container(
child: _buildButton(context),
));
} Widget _buildButton(BuildContext context) {
return new RaisedButton(
padding: new EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 10.0),
//padding
child: new Text(
'show dialog',
style: new TextStyle(
fontSize: 18.0, //textsize
color: Colors.white, // textcolor
),
),
color: Theme.of(context).accentColor,
elevation: 4.0,
//shadow
splashColor: Colors.blueGrey,
onPressed: () {
showAlertDialog(context);
});
}
void showAlertDialog(BuildContext context) {
NavigatorState navigator= context.rootAncestorStateOfType(const TypeMatcher<NavigatorState>());
debugPrint("navigator is null?"+(navigator==null).toString()); showDialog(
context: context,
builder: (_) => new AlertDialog(
title: new Text("Dialog Title"),
content: new Text("This is my content"),
actions:<Widget>[
new FlatButton(child:new Text("CANCEL"), onPressed: (){
Navigator.of(context).pop(); },),
new FlatButton(child:new Text("OK"), onPressed: (){
Navigator.of(context).pop(); },)
]
));
}

至于为什么flutter里的对话框控件对BuildContext的要求这么严格,暂时还不清楚原因。

后记:

在flutter里,Widget,Element和BuildContext之间的关系是什么呢?

摘抄部分系统源码如下:

abstract class Element extends DiagnosticableTree implements BuildContext{....}

abstract class ComponentElement extends Element {}

class StatelessElement extends ComponentElement {
@override
Widget build() => widget.build(this);
} class StatefulElement extends ComponentElement {
@override
Widget build() => state.build(this);
} abstract class Widget extends DiagnosticableTree {
Element createElement();
} abstract class StatelessWidget extends Widget {
@override
StatelessElement createElement() => new StatelessElement(this);
@protected
Widget build(BuildContext context);
} abstract class StatefulWidget extends Widget {
@override
StatefulElement createElement() => new StatefulElement(this);
@protected
State createState();
}
abstract class State<T extends StatefulWidget> extends Diagnosticable {
@protected
Widget build(BuildContext context);
}

flutter dialog异常Another exception was thrown: Navigator operation requested with a context that does not include a Navigator的更多相关文章

  1. flutter: Another exception was thrown: Navigator operation requested with a context that does not include a Navigator.

    import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends State ...

  2. flutter dialog异常Another exception was thrown: No MaterialLocalizations found

    flutter dialog异常Another exception was thrown: No MaterialLocalizations found import 'package:flutter ...

  3. Flutter Navigator operation requested with a context that does not include a Navigat

    如下直接在 MaterialApp 中使用 Navigator 是会报 Navigator operation requested with a context that does not inclu ...

  4. flutter SnackBar异常Another exception was thrown: Scaffold.of() called with a context that does not contain a Scaffold

    代码如下: import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( title: 'Returning Da ...

  5. Could not create the view: An unexpected exception was thrown的解决方法

    MyEclipse下面的server窗口突然不能正常显示了,而且还显示Could not create the view: An unexpected exception was thrown(无法创 ...

  6. Python中的异常(Exception)处理

    异常 当你的程序出现例外情况时就会发生异常(Exception).例如,当你想要读取一个文件时,而那个文件却不存在,怎么办?又或者你在程序执行时不小心把它删除了,怎么办?这些通过使用异常来进行处理. ...

  7. flutter dialog

    flutter Dialog import 'dart:math'; import 'package:flutter/material.dart'; import 'test.dart'; impor ...

  8. [C#] C# 知识回顾 - 你真的懂异常(Exception)吗?

    你真的懂异常(Exception)吗? 目录 异常介绍 异常的特点 怎样使用异常 处理异常的 try-catch-finally 捕获异常的 Catch 块 释放资源的 Finally 块 一.异常介 ...

  9. myEclipse Could not create the view: An unexpected exception was thrown.

    myEclipse 非正常关闭,打开后 service Explorer or Package Explorer 视图显示不出来.报“Could not create the view: An une ...

随机推荐

  1. Win7 Linux双系统,恢复Linux启动项

    在一台电脑上安装Win7 Centos双系统,先安装Win,再安装Centos7.装完后,丢失Linux启动项. 恢复步骤,下载EasyBCD,添加新条目,操作系统选择Linux/BSD,类型选择GR ...

  2. 001-SaltStack入门篇(一)之SaltStack部署

    早期运维工作中用过稍微复杂的Puppet,下面介绍下更为简单实用的Saltstack自动化运维的使用. Saltstack知多少Saltstack是一种全新的基础设施管理方式,是一个服务器基础架构集中 ...

  3. zencart 输出产品特价折扣百分比

    通过调用zen_get_products_base_price($products_id)获取原价,zen_get_products_special_price($products_id)获取特价,进 ...

  4. Atcoder grand 025 组合数学塔涂色 贪心走路博弈

    A 略 B 题意:给你N个数(3e5) 每个数可以是0,a,b,a+b(3e5) 但是总数加起来要是定值K(18e10) 问总方法数mod 998244353 解: 把a+b的看成是一个a加上一个b的 ...

  5. Web Api 接口测试工具:Swagger

    前言:WebApi接口开发完毕后,交付给前端人员或手机端开发者时接口说明文档是必不可少的配套设备,如果公司流程不规范大家使用口口相传的交接方式,而且没有改进的欲望,那你可以到此为止了.Swagger是 ...

  6. 玩蛇记之用python实现易宝快速支付接口

    玩蛇记之用python实现易宝快速支付接口 现在很多这种快速支付的通道,易宝支持的通道算是很全面的,正好最近需要集成易宝的支付通道到平台中,所以写一贴来记录一下,顺便鄙视一下国内的支付平台,api的支 ...

  7. vue导航菜单动态展示

    地址:https://blog.csdn.net/qq_31126175/article/details/81875468      

  8. JAVA笔记28-正则表达式(补充、不重要)

    一.Greedy(贪婪的)尽可能多的匹配,Reluctant(不情愿的)尽可能少的匹配.Possessive(独占的)不常用. Greedy 数量词 X? X,一次或一次也没有 X* X,零次或多次 ...

  9. Linux基本命令+Makefile

    1.linux下查看进程占用cpu的情况(top): 格式 top [-] [d delay] [q] [c] [S] [s] [i] [n] 主要参数 d:指定更新的间隔,以秒计算. q:没有任何延 ...

  10. matlab中画三维图形

    这里主要讲述两个方法用matlab画三维图形: 1.mesh函数 先看一个简单的例子: x = ::; y = ::; [X, Y] = meshgrid(x, y); Z = zeros(,); Z ...