Flutter 异常: The getter ‘modalBarrierDismissLabel’ was called on null. Receiver: null Tried calling:
一般出现这种问题都是直接在 MaterialApp
层显示 Dialog
造成的,因为显示 Dialog
传入的是 MaterialApp
层的 context
,所以会出现这种错误。
1.问题场景
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Demo'),
),
body: Center(
child: RaisedButton(
onPressed: () {
showCupertinoDialog(
///此处传入的是 MaterialApp 的 context
context: context,
builder: (context) {
/// 此处省略弹窗代码
}
}
},
child: Text('点击显示弹窗'),
),
),
),
);
}
}
因为 context
是 MaterialApp
的,所以会报这样的错:
════════ Exception caught by gesture ════════
The following NoSuchMethodError was thrown while handling a gesture:
The getter 'modalBarrierDismissLabel' was called on null.
Receiver: null
Tried calling: modalBarrierDismissLabel
2.解决方案
直接在 MaterialApp
的 home
中在传入一个继承于 StatelessWidget
或者是 StatefulWidget
的部件即可。如:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: DialogPage(),
);
}
}
class DialogPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Demo'),
),
body: Center(
child: RaisedButton(
onPressed: () {
_showDialog(context);
},
child: Text('点击显示弹窗'),
),
),
);
}
}
void _showDialog(widgetContext) {
/// 显示 IOS 风格的 CupertinoAlertDialog
showCupertinoDialog(
context: widgetContext,
builder: (context) {
return CupertinoAlertDialog(
title: Text('确认删除'),
actions: [
CupertinoDialogAction(
child: Text('确认'),
onPressed: () {
Navigator.of(context).pop();
},
),
CupertinoDialogAction(
child: Text('取消'),
isDestructiveAction: true,
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}