S.of(context)返回null

时间:2019-08-21 17:51:26

标签: flutter flutter-layout

版本1:

 @override
  void initState() {
    super.initState();

    slides.add(
      new Slide(
        title: S.of(context).intro_title_first,
        description: S.of(context).intro_description_first,
        pathImage:"images/image1",

        /*pathImage: "assets/images/intro_1.xml",*/

        backgroundColor: Color(0xfff5a623),
      ),
    );
}

运行此代码时,出现错误:

I/flutter ( 9492): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 9492): The following assertion was thrown building Builder:
I/flutter ( 9492): inheritFromWidgetOfExactType(_LocalizationsScope) or inheritFromElement() was called before
I/flutter ( 9492): IntroScreenState.initState() completed.
I/flutter ( 9492): When an inherited widget changes, for example if the value of Theme.of() changes, its dependent
I/flutter ( 9492): widgets are rebuilt. If the dependent widget's reference to the inherited widget is in a constructor
I/flutter ( 9492): or an initState() method, then the rebuilt dependent widget will not reflect the changes in the
I/flutter ( 9492): inherited widget.
I/flutter ( 9492): Typically references to inherited widgets should occur in widget build() methods. Alternatively,
I/flutter ( 9492): initialization based on inherited widgets can be placed in the didChangeDependencies method, which
I/flutter ( 9492): is called after initState and whenever the dependencies change thereafter.

因此,在搜索堆栈溢出后,我得到了this link

然后代码变为:

版本2:

@override
  void initState() {
    super.initState();

    Future.delayed(const Duration(milliseconds: 500), () {
      setState(() {
        // Here you can write your code for open new view

        slides.add(
          new Slide(
            title: S.of(context).intro_title_first,
            description: S.of(context).intro_description_first,
            pathImage:"images/image1",

            /*pathImage: "assets/images/intro_1.xml",*/

            backgroundColor: Color(0xfff5a623),
          ),
        );

      });
    });

  }

然后我得到了错误:

The following assertion was thrown building IntroSlider(dirty, dependencies: [MediaQuery,
I/flutter ( 9492): _LocalizationsScope-[GlobalKey#bb3bb]], state: IntroSliderState#f24e7(ticker inactive)):
I/flutter ( 9492): 'package:flutter/src/widgets/container.dart': Failed assertion: line 267 pos 15: 'margin == null ||
I/flutter ( 9492): margin.isNonNegative': is not true.
I/flutter ( 9492): 

问题:

  1. 在版本1的代码中,我相信我会出错,因为buildContext直到那时才可用,但是作为mentioned here,在initstate方法中(如果已安装)则存在buildContext。
  2. 在版本2代码中,S.of(context)返回null。

Blockquote

1 个答案:

答案 0 :(得分:1)

遇到相同的问题,我所做的是创建一个扩展“ S”的类,覆盖方法“ of”,该方法返回null并使用“ S”的“当前”属性。

class R extends S {
  static of(BuildContext context) {
    return S.current;
  }
}

现在我用

R.of(context).app_name

猜猜是什么?有效! 我通过更改语言并再次打开应用程序进行了测试,它的工作原理很吸引人,正确地更改了语言。不知何故,属性“当前”保留了“ of”的正确实现,我只是用它来帮助我。 希望对您有所帮助。