Flutter路由跳转报错:Widget树无S实例,是否添加S.delegate?
解决Flutter路由跳转时的S类实例缺失错误
你遇到的No instance of S present in the widget tree. Did you add S.delegate in localizationsDelegates?错误,是因为项目启用了国际化,但未在全局App配置中正确注册本地化代理类。
具体修复步骤:
- 找到项目中的
MaterialApp(或CupertinoApp/WidgetsApp)配置代码,在localizationsDelegates中添加S.delegate,同时将supportedLocales设置为S.delegate.supportedLocales,示例如下:
MaterialApp( localizationsDelegates: const [ S.delegate, // 关键:添加该本地化代理 GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: S.delegate.supportedLocales, // 使用S类提供的支持语言列表 home: const YourInitialPage(), // 你的初始页面 );
- 若
S类是通过flutter_gen生成的,确认已执行flutter pub run build_runner build命令,生成完整的本地化代码文件。 - 跳转后的
MyHomePage页面已处于MaterialApp子树中(你的跳转代码已满足此条件),无需额外修改,确保页面内调用S.of(context)时能正常获取实例即可。
内容的提问来源于stack exchange,提问作者angelina
相关产品推荐
相关产品推荐

