rrousselGit/flutter_hooks

Examples for complex cases with useState hook

开放

#347 创建于 2023年3月10日

 (9 条评论) (0 个反应) (1 位负责人)Dart (193 个派生)github user discovery
documentationgood first issue

仓库指标

星标
 (3,325 个星标)
PR 合并指标
 (30 天内没有已合并 PR)

描述

Describe what scenario you think is uncovered by the existing examples/articles

Hello! I'm new to Dart and Flutter, but I've used React a lot. Since this library is a port of React hooks, I'd suggest to provide more examples of how hooks could be used. Especially the cases, where it's different from react. I'd suggest to have an example section, which could be filled with the help of the community.

Describe why existing examples/articles do not cover this case

I struggle to understand even such a simple hook as useState in Flutter. It seems that Dart (or Flutter, or this library) behave different from React hooks when complex objects are passed.

For example, I specifically struggle with this situation: I have a Sealed Union built by freezed as a representation of the state. When the exercise prop is passed, I expect the state to initialise. This works for the render of the widget. However, after the exercise prop changes in the parent widget, the state keeps the previous value.

I'm not sure what is the issue. Maybe I misunderstand how Flutter works, but I'd definitely expect the desired behaviour in React.

Code for reference:

// ...
@freezed
class Answer with _$Answer {
  const factory Answer.valid(String value) = Valid;
  const factory Answer.invalid(String value) = Invalid;
}

@freezed
class FormState with _$FormState {
  const factory FormState.initial(MultipleChoiceExercise exercise) = Initial;
  const factory FormState.answered(Answer answer) = Answered;
  const factory FormState.showingCorrect(
      Answer answer, MultipleChoiceExercise exercise) = ShowingCorrect;
}

class MultipleChoiceForm extends HookWidget {
  final MultipleChoiceExercise exercise;

  const MultipleChoiceForm({
    required this.exercise,
// ...
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final formState = useState<FormState>(FormState.initial(exercise));
    // ...

It would be wonderful to have complex cases as examples somewhere in the docs. I'd gladly contribute myself, if you agree with the notion proposed.

贡献者指南