Skip to content

Instantly share code, notes, and snippets.

@rizumita
Created October 18, 2023 22:12
Show Gist options
  • Save rizumita/8752dddf610475558f4ef5dd709a386a to your computer and use it in GitHub Desktop.
Save rizumita/8752dddf610475558f4ef5dd709a386a to your computer and use it in GitHub Desktop.
Not using useReducer
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'];
enum Stage { dropdown1, textInput, dropdown2, finished }
class MyFormUseStateView extends HookWidget {
const MyFormUseStateView({super.key});
@override
Widget build(BuildContext context) {
final dropdown1Value = useState<String?>(null);
final textInputController = useTextEditingController();
final dropdown2Value = useState<String?>(null);
final stage = useState<Stage>(Stage.dropdown1);
final formKey = useState(GlobalKey<FormState>());
return Form(
key: formKey.value,
child: Center(
child: Column(
children: <Widget>[
if (stage.value == Stage.dropdown1 || stage.value == Stage.textInput || stage.value == Stage.dropdown2)
DropdownButton<String>(
value: dropdown1Value.value,
items:
itemsForDropdown1.map((item) => DropdownMenuItem<String>(value: item, child: Text(item))).toList(),
onChanged: (value) {
dropdown1Value.value = value;
textInputController.clear();
stage.value = Stage.textInput;
},
),
if (stage.value == Stage.textInput)
Column(
children: <Widget>[
TextFormField(
controller: textInputController,
validator: (value) => validate(value),
),
ElevatedButton(
onPressed: () {
if (formKey.value.currentState!.validate()) {
stage.value = Stage.dropdown2;
}
},
child: const Text('Submit'),
),
],
),
if (stage.value == Stage.dropdown2) ...[
Text(textInputController.text),
DropdownButton<String>(
value: dropdown2Value.value,
items:
itemsForDropdown2.map((item) => DropdownMenuItem<String>(value: item, child: Text(item))).toList(),
onChanged: (value) {
dropdown2Value.value = value;
stage.value = Stage.finished;
},
),
],
if (stage.value == Stage.finished)
Column(
children: <Widget>[
Text('Dropdown 1: ${dropdown1Value.value}'),
Text('Text Input: ${textInputController.text}'),
Text('Dropdown 2: ${dropdown2Value.value}'),
ElevatedButton(
onPressed: () {
dropdown1Value.value = null;
textInputController.clear();
dropdown2Value.value = null;
stage.value = Stage.dropdown1;
},
child: const Text('Reset'),
),
],
),
],
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment