Flutter Toast插件报错"No overlay widget found",登录校验Toast无法显示
解决Toast无法显示(No Overlay widget found)问题
错误原因
你在MyApp的build方法中执行ToastContext().init(context)时,使用的是MyApp组件的上下文——而MyApp是MaterialApp的父组件,这个上下文不包含Overlay(Overlay是MaterialApp内部自动创建的组件,Toast依赖它来显示),所以触发校验时Toast找不到Overlay,抛出异常。
两种修复方案
方案一:修正ToastContext的初始化位置
把ToastContext().init(context)移到MaterialApp内部的组件中,确保使用包含Overlay的上下文。修改MyApp的代码:
class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'm-Inwentaryzacja', theme: ThemeData( primarySwatch: Colors.blue, primaryColor: Colors.white, accentColor: Colors.black, backgroundColor: Color.fromARGB(255, 0, 36, 66), buttonTheme: ButtonThemeData( buttonColor: Color.fromARGB(255, 190, 2, 58), ), ), // 用Builder获取MaterialApp内部的context home: Builder( builder: (context) { ToastContext().init(context); return const LoginForm(title: 'm-Inwentaryzacja'); }, ), routes: { SignUpForm.routeName: (ctx) => SignUpForm(), }, ); } }
方案二:调用Toast时直接传入当前页面的上下文
不需要全局初始化ToastContext,直接在调用Toast时传入当前页面的上下文。修改toastHelper.dart:
import 'package:flutter/material.dart'; import 'package:toast/toast.dart'; alertDialog(BuildContext context, String msg) { Toast.show( msg, duration: Toast.lengthLong, gravity: Toast.bottom, context: context, // 传入当前页面的context ); }
同时删掉MyApp中ToastContext().init(context)这行代码。
验证
两种方案都能解决问题,推荐方案二——它更灵活,每个页面使用自己的上下文,避免全局上下文带来的潜在问题。
内容的提问来源于stack exchange,提问作者OnePanic
相关产品推荐
相关产品推荐

