【发布时间】:2019-12-27 00:59:33
【问题描述】:
版本 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 代码中,我相信我收到了错误,因为 buildContext 在此之前不可用,但作为 mentioned here,在 initstate 方法中,如果已安装则 buildContext 存在。
- 在版本 2 代码中,S.of(context) 返回 null。
块引用
【问题讨论】:
-
不要在
initState中构建小部件(假设Slide是小部件)。它们应该建在build。 -
@RichardHeap 那么为什么会出现负边距错误
-
确保您正确启动了本地化。
localizationsDelegates: [ S.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: S.delegate.supportedLocales,