Flutter开发报错:Drawer关联AppBar提示找不到Overlay组件
错误信息
========= 组件库捕获到异常 =======================================================
构建Tooltip("Open navigation menu", dirty, state: TooltipState#1bb77(ticker inactive))时抛出如下断言:
未找到Overlay widget。Tooltip组件需要有Overlay组件祖先才能正常工作。
向应用添加Overlay最常见的方式是在runApp()调用中包含MaterialApp或Navigator组件。
未找到overlay的具体组件是:Tooltip
"Open navigation menu"
引发错误的相关组件是:
AppBar AppBar:file:///Users/sherzad/Desktop/Programmierung/flutter_projekte/taalamna_projekt/taalamna/lib/my_app.dart:44:21
错误截图

原代码
class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { // final MyAppController controller = Get.put(MyAppController()); @override Widget build(BuildContext context) { return FirebasePhoneAuthProvider( child: GetMaterialApp( title: 'Flutter Demo', localizationsDelegates: const [ GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, S.delegate, ], supportedLocales: S.delegate.supportedLocales, // locale: Locale("ar"), //for testing translation theme: ThemeData( primarySwatch: Colors.blue, ), debugShowCheckedModeBanner: false, builder: (context, child) { // return controller.buildScaffold(child); return Scaffold( appBar: AppBar(), drawer: Drawer(), body: child, ); }, home: // LoginScreen() // SplashScreen() FlavorConfig.getFlavorName() == FLAVOUR_DEV ? const HomeScreen() : const SplashScreen(), ), ); } }
问题原因
你在GetMaterialApp的builder中直接返回了Scaffold,但GetMaterialApp内部的Overlay是在builder的child层级之上的。AppBar自带的抽屉按钮(其Tooltip依赖Overlay)此时处于Overlay的上层,无法找到所需的Overlay祖先节点,因此触发断言错误。
解决方法
方案1:将Scaffold移至页面层级(推荐)
移除builder中的Scaffold,把它放到home对应的页面结构里,确保AppBar处于GetMaterialApp的Overlay范围内:
class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { // final MyAppController controller = Get.put(MyAppController()); @override Widget build(BuildContext context) { return FirebasePhoneAuthProvider( child: GetMaterialApp( title: 'Flutter Demo', localizationsDelegates: const [ GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, S.delegate, ], supportedLocales: S.delegate.supportedLocales, // locale: Locale("ar"), //for testing translation theme: ThemeData( primarySwatch: Colors.blue, ), debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar(), drawer: Drawer(), body: FlavorConfig.getFlavorName() == FLAVOUR_DEV ? const HomeScreen() : const SplashScreen(), ), ), ); } }
方案2:在builder中手动添加Overlay
如果需要通过builder统一处理页面框架,可以手动在Scaffold外层套一层Overlay,确保Tooltip能找到所需的祖先:
builder: (context, child) { return Overlay( initialEntries: [ OverlayEntry( builder: (context) => Scaffold( appBar: AppBar(), drawer: Drawer(), body: child, ), ), ], ); },
内容的提问来源于stack exchange,提问作者skm

