本文介绍了Localizations.of从StatelessWidget返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,如果小部件类是从 StatelessWidget

As the title said, if the widget class is extended from StatelessWidget

Localizations.of<MaterialLocalizations>(context, MaterialLocalizations);

任何想法都会返回null吗?

will return null any ideas?

推荐答案

也遇到了同样的问题.在flutter存储库中有一个未解决的 github问题.对我来说唯一解决的办法就是创建一个分离的小部件,如下所示:

had the same problem. Theres an open github issue in the flutter repository. Only thing that solved it for me was creating a separat widget like this:

@override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        localizationsDelegates: [...],
        supportedLocales: ..,
        locale: ...,
        home: MyAppPage()); // separat MyAppPage instead of putting widget code with translations here
  }

// MyAppPage
class MyAppPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        ...
        body: Center(
            child: Text(AppTranslations.of(context).translate(...)),

如果这不能解决您的问题,我们可能需要查看更多代码:)!

If this is not solving your problem we maybe need to see more code :)!

这篇关于Localizations.of从StatelessWidget返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:28