Flutterでアプリを開発する時に以下のエラーがでました。
- ソースコード
Expanded(child: GestureDetector(child: HamburgeMenu(),onTap:onSideMenuSelect(),), flex: 10)
onSideMenuSelect(){
this.setState((){
sideMenuShow = false;
});
}
- エラーメッセージ
flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building TopNavigation(dirty, state: TopNavigationState#fef9e):
flutter: setState() or markNeedsBuild() called during build.
flutter: This HomeStatePage widget cannot be marked as needing to build because the framework is already in
flutter: the process of building widgets. A widget can be marked as needing to be built during the build
flutter: phase only if one of its ancestors is currently building. This exception is allowed because the
flutter: framework builds parent widgets before children, which means a dirty descendant will always be
flutter: built. Otherwise, the framework might not visit this widget during this build phase.
flutter: The widget on which setState() or markNeedsBuild() was called was:
flutter: HomeStatePage
flutter: The widget which was currently being built when the offending call was made was:
flutter: TopNavigation
flutter:
- 原因
本来的には
onTap:メソッド名、これにより、Widgetを作る時にメソッド体を登録する
ここでは
onTap:メソッド名()、これにより、Widgetを作る時にメソッドが実行された。メソッドの中にStateを変えようとした。でも、この時はWidgetを作る時(ビルド時)だった。ビルド時にはStateを変えてはいけないから、エラーが出てきたわけだ。
- 解決方法1
引数がない場合は
そのままメソッド名を渡せばいい
Expanded(child: GestureDetector(child: HamburgeMenu(),onTap:onSideMenuSelect,), flex: 10)
- 解決方法2
引数がある場合は
onTap:(){ run(parameters) }の書き方でいい
Expanded(child: GestureDetector(child: HamburgeMenu(),onTap:(){ onSideMenuSelect(true); },), flex: 10)
onSideMenuSelect(res){
this.setState((){
sideMenuShow = res;
});
}
ありがとうございます。