Flutterando / triple_pattern

Segmented State Pattern for Reactive Property
MIT License
160 stars 36 forks source link

Problem with use HydratedMixin #72

Closed skiryuk closed 2 years ago

skiryuk commented 2 years ago

Hi!

I am using HydratedMixin to restore the last state after routing. The idea is cool :))

There is a problem that the state is restored after building the widgets, which in some cases leads to problems (see the code below)

For example, we use the CupertinoTextFormFieldRow widget as part of the CupertinoFormSection. It has an initialValue property (default value on first build).

When the state is restored, it happens so that initialValue = null, and then after a while initialValue = valueFromPrefs. But since the first construction has already been (an element with a state has been created), the second initialValue is no longer taken into account

Page

class NotifiesPage extends StatefulWidget {
  static const routeName = '/notifies-page';

  @override
  State<NotifiesPage> createState() => _NotifiesPageState();
}

class _NotifiesPageState extends ModularState<NotifiesPage, NotifiesPageStore> {
  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      child: SafeArea(
        child: ScopedBuilder<NotifiesPageStore, Exception, NotifiesPageState>(
          store: store,
          onState: (context, state) => Column(
            children: [
              Text('notifies_page'),
              CupertinoFormSection.insetGrouped(
                header: Text('Text'),
                children: <Widget>[
                  CupertinoTextFormFieldRow(
                    initialValue: state.text,
                    onChanged: (value) => store.setText(value),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Store

class NotifiesPageStore extends NotifierStore<Exception, NotifiesPageState>
    with HydratedMixin {
  NotifiesPageStore() : super(NotifiesPageState());

  setText(String? text) {
    update(NotifiesPageState(text: text));
  }
}

State

class NotifiesPageState implements Serializable<NotifiesPageState> {
  final String? text;

  NotifiesPageState({this.text});

  @override
  NotifiesPageState fromMap(Map<String, dynamic> map) =>
      NotifiesPageState(text: map['text']);

  @override
  Map<String, dynamic> toMap() => {'text': text};
}

Is there some way to wait for the store to be restored before the first build? What other solutions could there be?

jacobaraujo7 commented 2 years ago

Hello. In v1.4.0 you can use HydratedMixin.hasInitialized flag. Thank you.