I pass isSendEmail boolean variable to another AboutPageWidget widget, in this widget I change the value of this variable and I want it to return to screen 1, how to do that, how to get the value of isSendEmail variable on screen 1?
screen 1
Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
AboutPageWidget(isSendEmail: isSendEmail),
const SizedBox(
height: 42,
),
isSendEmail
? SetNewPasswordFields(
newPasswordCubit: newPasswordCubit,
)
: const EmailFieldWidget(),
],
),
screen 2
class AboutPageWidget extends StatefulWidget {
AboutPageWidget({
Key? key,
required this.isSendEmail,
}) : super(key: key);
bool isSendEmail;
@override
State<AboutPageWidget> createState() => _AboutPageWidgetState();
}
class _AboutPageWidgetState extends State<AboutPageWidget> {
@override
Widget build(BuildContext context) {
return Column(
children: [
Row(
children: [
Expanded(
flex: 1,
child: Align(
alignment: Alignment.centerLeft,
child: IconButton(
onPressed: () => widget.isSendEmail
? setState(
() => widget.isSendEmail = !widget.isSendEmail,
)
: _onBackPressed(context),
>Solution :
You must define a callback in the screen2 then listen to it on screen.
For example:
Screen1:
Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
AboutPageWidget(
isSendEmail: isSendEmail,
isSendEmailChanged: (value) => setState(() => isSendEmail = value);
),
const SizedBox(
height: 42,
),
isSendEmail
? SetNewPasswordFields(
newPasswordCubit: newPasswordCubit,
)
: const EmailFieldWidget(),
],
),
Screen2:
class AboutPageWidget extends StatefulWidget {
AboutPageWidget({
Key? key,
required this.isSendEmail,
required this.isSendEmailChanged,
}) : super(key: key);
ValueChanged<bool> isSendEmailChanged;
bool isSendEmail;
@override
State<AboutPageWidget> createState() => _AboutPageWidgetState();
}
class _AboutPageWidgetState extends State<AboutPageWidget> {
@override
Widget build(BuildContext context) {
return Column(
children: [
Row(
children: [
Expanded(
flex: 1,
child: Align(
alignment: Alignment.centerLeft,
child: IconButton(
onPressed: () => widget.isSendEmail
? widget.isSendEmailChanged(!widget.isSendEmail)
: _onBackPressed(context),
Then inside _AboutPageWidgetState whenever you want to emit that isSendEmail has changed, just call widget.isSendEmailChanged with the new value.
For more complex states, I’d recommend using Provider or some other state management solution.