Created
October 18, 2023 22:14
-
-
Save rizumita/fa1ca1b265d7bc7f4c37ad10d0d9ed61 to your computer and use it in GitHub Desktop.
Using useReducer code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:flutter_hooks/flutter_hooks.dart'; | |
import 'package:use_reducer_example/reducer.dart'; | |
final itemsForDropdown1 = ['A', 'B', 'C']; | |
final itemsForDropdown2 = ['1', '2', '3']; | |
class MyFormUseReducerView extends HookWidget { | |
const MyFormUseReducerView({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
final MyFormStore store = useReducer( | |
reducer, | |
initialState: MyFormState(GlobalKey<FormState>(), useTextEditingController()), | |
initialAction: const ResetAction(), | |
); | |
return Form( | |
key: store.state.formKey, | |
child: Center( | |
child: Column( | |
children: [ | |
if (store.state case MyFormState(:final dropdown1Value) when !store.state.isFinished) | |
DropdownButton<String>( | |
value: dropdown1Value, | |
items: | |
itemsForDropdown1.map((item) => DropdownMenuItem<String>(value: item, child: Text(item))).toList(), | |
onChanged: (value) => store.dispatch(Dropdown1ChangedAction(value!)), | |
), | |
if (store.state case MyFormState(:final dropdown1Value?, textInput: null)) ...[ | |
TextFormField( | |
controller: store.state.textInputController, | |
validator: (value) => (store..dispatch(const ValidateTextInputAction())).state.error, | |
), | |
ElevatedButton( | |
onPressed: () => store.state.formKey.currentState!.validate(), | |
child: const Text('Submit'), | |
), | |
], | |
if (store.state case MyFormState(textInput: final textInput?, dropdown2Value: null)) ...[ | |
Text(textInput), | |
DropdownButton<String>( | |
value: store.state.dropdown2Value, | |
items: | |
itemsForDropdown2.map((item) => DropdownMenuItem<String>(value: item, child: Text(item))).toList(), | |
onChanged: (value) => store.dispatch(Dropdown2ChangedAction(value!)), | |
), | |
], | |
if (store.state | |
case MyFormState(:final dropdown1Value?, :final textInput?, error: null, :final dropdown2Value?)) ...[ | |
Text('Dropdown 1: $dropdown1Value'), | |
Text('Text Input: $textInput'), | |
Text('Dropdown 2: $dropdown2Value'), | |
ElevatedButton( | |
onPressed: () => store.dispatch(const ResetAction()), | |
child: const Text('Reset'), | |
), | |
], | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment