setState() or markNeedsBuild() called during build
Initially I want to know why onPress call automatically while rendering. After getting above issue I tried solving it in a number of ways like
WidgetsBinding.instance.addPostFrameCallback and Future.delayed . Code
class ShadowBtn {
static Widget drawBtn(double width, double height, String text, myFunc) {
return Container(
width: width,
height: height,
child: ElevatedButton(
///onPressed: () => myFunc,
onPressed: () {
myFunc();
},
child: Text(text),
),
),
);
}
}
Some solutions said to update onPress like
onPressed: () => myFunc
I simply call it like
ShadowBtn.drawBtn(321.w, 61.h, "SEND OTP", openScreen(context))
Where openScreen
openScreen(context) {
Future.delayed(Duration.zero, () async {
Navigator.of(context)
.pushNamedAndRemoveUntil('/dashboard', (Route<dynamic> route) => false);
});
// WidgetsBinding.instance.addPostFrameCallback((_) {
// Navigator.of(context).pushNamedAndRemoveUntil(
// '/dashboard', (Route<dynamic> route) => false);
// });
}
After trying all the solution. I didn't find any proper way to handle it.
CodePudding user response:
openScreen
function is called when passed as a parameter.
ShadowBtn.drawBtn(321.w, 61.h, "SEND OTP", openScreen(context))
Something like this should work:
ShadowBtn.drawBtn(321.w, 61.h, "SEND OTP", () => openScreen(context));
class ShadowBtn {
static Widget drawBtn(double width, double height, String text, void Function() myFunc) {
...
onPressed: () {
myFunc();
},
...
}
}
CodePudding user response:
While passing the parameter you are actually not passing , instead making a function call
, but function definition
needs to be passed in the parameter
.
so try using (){function()}
, so now the definition
is passed, and function is not called.
Change
ShadowBtn.drawBtn(321.w, 61.h, "SEND OTP", openScreen(context))
to
ShadowBtn.drawBtn(321.w, 61.h, "SEND OTP", (){openScreen(context)})