I am new to Flutter and just playing around to understand the working of this framework. So the code below doesn't make much sense.
I am trying to display a snack bar as soon as the app loads by calling a child widget.
Here's the code :
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Demo')),
body: GetSnackBarWidget(),
),
);
}
}
class GetSnackBarWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
final snackBar = SnackBar(content: Text("SnackBar"));
Scaffold.of(context).showSnackBar(snackBar);
return Text("returned");
}
}
But I am getting the following Exception :
I/flutter ( 3781): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 3781): The following assertion was thrown building GetSnackBarWidget(dirty):
I/flutter ( 3781): setState() or markNeedsBuild() called during build.
I/flutter ( 3781): This Scaffold widget cannot be marked as needing to build because the framework is already in the
I/flutter ( 3781): process of building widgets. A widget can be marked as needing to be built during the build phase
I/flutter ( 3781): only if one of its ancestors is currently building. This exception is allowed because the framework
I/flutter ( 3781): builds parent widgets before children, which means a dirty descendant will always be built.
I/flutter ( 3781): Otherwise, the framework might not visit this widget during this build phase.
I/flutter ( 3781): The widget on which setState() or markNeedsBuild() was called was:
I/flutter ( 3781): Scaffold(dependencies: [_LocalizationsScope-[GlobalKey#33728], Directionality, _InheritedTheme,
I/flutter ( 3781): MediaQuery], state: ScaffoldState#dbc9e(tickers: tracking 2 tickers))
I/flutter ( 3781): The widget which was currently being built when the offending call was made was:
I/flutter ( 3781): GetSnackBarWidget(dirty)
Can someone explain in detail what's happening?