Flutter 异常: The getter ‘modalBarrierDismissLabel’ was called on null. Receiver: null Tried calling:

Myth丶恋晨 2023-02-14 13:08 147阅读 0赞

Flutter 异常: The getter ‘modalBarrierDismissLabel’ was called on null. Receiver: null Tried calling:

  • 1.问题场景
  • 2.解决方案

一般出现这种问题都是直接在 MaterialApp 层显示 Dialog 造成的,因为显示 Dialog 传入的是 MaterialApp 层的 context,所以会出现这种错误。

1.问题场景

  1. import 'package:flutter/cupertino.dart';
  2. import 'package:flutter/material.dart';
  3. void main() {
  4. runApp(MyApp());
  5. }
  6. class MyApp extends StatelessWidget {
  7. @override
  8. Widget build(BuildContext context) {
  9. return MaterialApp(
  10. home: Scaffold(
  11. appBar: AppBar(
  12. title: Text('Demo'),
  13. ),
  14. body: Center(
  15. child: RaisedButton(
  16. onPressed: () {
  17. showCupertinoDialog(
  18. ///此处传入的是 MaterialApp 的 context
  19. context: context,
  20. builder: (context) {
  21. /// 此处省略弹窗代码
  22. }
  23. }
  24. },
  25. child: Text('点击显示弹窗'),
  26. ),
  27. ),
  28. ),
  29. );
  30. }
  31. }

因为 contextMaterialApp 的,所以会报这样的错:

  1. ════════ Exception caught by gesture ════════
  2. The following NoSuchMethodError was thrown while handling a gesture:
  3. The getter 'modalBarrierDismissLabel' was called on null.
  4. Receiver: null
  5. Tried calling: modalBarrierDismissLabel

2.解决方案

直接在 MaterialApphome 中在传入一个继承于 StatelessWidget 或者是 StatefulWidget 的部件即可。如:

  1. import 'package:flutter/cupertino.dart';
  2. import 'package:flutter/material.dart';
  3. void main() {
  4. runApp(MyApp());
  5. }
  6. class MyApp extends StatelessWidget {
  7. @override
  8. Widget build(BuildContext context) {
  9. return MaterialApp(
  10. home: DialogPage(),
  11. );
  12. }
  13. }
  14. class DialogPage extends StatelessWidget {
  15. @override
  16. Widget build(BuildContext context) {
  17. return Scaffold(
  18. appBar: AppBar(
  19. title: Text('Demo'),
  20. ),
  21. body: Center(
  22. child: RaisedButton(
  23. onPressed: () {
  24. _showDialog(context);
  25. },
  26. child: Text('点击显示弹窗'),
  27. ),
  28. ),
  29. );
  30. }
  31. }
  32. void _showDialog(widgetContext) {
  33. /// 显示 IOS 风格的 CupertinoAlertDialog
  34. showCupertinoDialog(
  35. context: widgetContext,
  36. builder: (context) {
  37. return CupertinoAlertDialog(
  38. title: Text('确认删除'),
  39. actions: [
  40. CupertinoDialogAction(
  41. child: Text('确认'),
  42. onPressed: () {
  43. Navigator.of(context).pop();
  44. },
  45. ),
  46. CupertinoDialogAction(
  47. child: Text('取消'),
  48. isDestructiveAction: true,
  49. onPressed: () {
  50. Navigator.of(context).pop();
  51. },
  52. ),
  53. ],
  54. );
  55. },
  56. );
  57. }

发表评论

表情:
评论列表 (有 0 条评论,147人围观)

还没有评论,来说两句吧...

相关阅读