问题描述
报错描述
在flutter页面中使用点击事件 showBottomSheet 无效,控制台报错如下:
======== Exception caught by gesture ===============================================================
The following assertion was thrown while handling a gesture:
No Scaffold widget found.
MusicInfoPage widgets require a Scaffold widget ancestor.
The specific widget that could not find a Scaffold ancestor was: MusicInfoPage
dependencies: [_LocalizationsScope-[GlobalKey#de178]]
state: _MusicInfoPageState#63914
The ancestors of this widget were:
: GetMaterialApp
: ScreenUtilInit
: MyApp
...
Typically, the Scaffold widget is introduced by the MaterialApp or WidgetsApp widget at the top of your application widget tree.
示例报错代码
(垃圾csdn,代码块不支持dart)
错误原因
出现这个异常的原因是showBottomSheet需要Scaffold这个部件的context,而我们传递给this的context并不是Scaffold的context,而是整个Widget本身的context。
解决方案
第一种方案
把showBottomSheet替换成showModalBottomSheet 就不会出现这个问题。
第二种方案
如果你的业务场景必须使用到showBottomSheet即可采取这种方案;
正如错误所说,我们只要把Scaffold的context传递给这个函数即可。我们可以为Scaffold生成一个全局key,并在其context中运行 showBottomSheet就ok啦。
上代码: