How to keep stateful state when parent widget updated

63 views Asked by At

I have a parent widget that is updated and this parent has a child stateful widget which is rebuilt when a parent is updated, I want to prevent the child from rebuilding each time the parent is updated. I want to state object of the stateful widget preserves its state when the parent rebuilds. Can we do this?

Here is my parent widget which is connected to a cubit

class ExampleStateless extends StatelessWidget {
  const ExampleStateless({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocSelector<ExcersiceCubit, ExcersiceState, FetchRemoteDataStatus>(
      selector: (state) {
        return state.status;
      },
      builder: (context, remoteStatus) {
        // This widget rebuild with each state emited from the cubit.
        return Container(
          child: RadioButtons(
              onOptionChanged: context.read<ExcersiceCubit>().onChnageCallback),
        );
      },
    );
  }
}

Here is the child widget which is a stateful widget that I want to preserve its state when the parent widget named ExampleStateless is updated.

class RadioButtons extends StatefulWidget {
  const RadioButtons({super.key, required this.onOptionChanged});
  final VoidCallback onOptionChanged;

  @override
  State<RadioButtons> createState() => _RadioButtonsState();
}

class _RadioButtonsState extends State<RadioButtons> {
  String _selected = 'a';
  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Radio(
            value: 'a',
            groupValue: _selected,
            onChanged: (_) {
              setState(() {
                _selected = 'a';
              });
              widget.onOptionChanged();
            }),
        Radio(
            value: 'b',
            groupValue: _selected,
            onChanged: (_) {
              setState(() {
                _selected = 'b';
              });
              widget.onOptionChanged();
            })
      ],
    );
  }
}

Here is my cubit and its state for reference.

class ExcersiceCubit extends Cubit<ExcersiceState> {
  ExcersiceCubit() : super(ExcersiceState());

  void onChnageCallback() async {
    final stateA = ExcersiceState(status: FetchRemoteDataStatus.loading);
    emit(stateA);
    await Future.delayed(Duration(seconds: 1));
    final stateB = ExcersiceState(status: FetchRemoteDataStatus.success);
    emit(stateB);
  }
}
@immutable
class ExcersiceState {
  final FetchRemoteDataStatus status;
  const ExcersiceState({this.status = FetchRemoteDataStatus.initial});
}

How can I preserve the RadioButtons state when the parent updated, I thought the Key would be helpful but I couldn't figure out how I use Keys or which type of key is helpful in this situation.

Any help would be appreciated, thanks in advance.

0

There are 0 answers