FormController<TValue> constructor
- TValue value
Context for using the form.
How to use
First, initialize FormController with the values to be used in the form. In the example, Map is used, but it is safer to use an immutable class.
FormController should be saved using some state management method.
We will give key to the key
of Form and place the FormXX
widget under it.
Pass the value of FormController in the initialValue
of each form widget, and describe the process of rewriting the value of FormController in the onSaved
.
If the Submit button is pressed, validate is executed.
Each form's validate
is executed. Only when true
is returned from validate, onSaved
of each form is executed and the process of rewriting value of FormController is executed.
After that, execute the process of writing data to the server based on the value of FormController, etc.
フォームを利用していくためのコンテキスト。
基本的な使い方
まず、FormControllerにフォーム中で利用するための値を与えながら初期化します。 例ではMapが利用されてますが、immutableなクラスを利用したほうが安全です。
FormControllerはなにかしらの状態管理手法で保存してください。
Formのkey
にkeyを与え、その下にFormXX
ウィジェットを配置していきます。
それぞれのフォームウィジェットのinitialValue
にFormControllerのvalueを渡し、onSaved
にFormControllerのvalueを書き換える処理を記載します。
Submitボタンが押された場合、validateを実行します。
それぞれのフォームのvalidate
が実行されます。validateからtrue
が返された場合のみそれぞれのフォームのonSaved
が実行され、FormControllerのvalueを書き換える処理が走ります。
その後、FormControllerのvalueを元にサーバーにデータを書き込む処理等を実行してください。
class FormPage extends StatefulWidget {
const FormPage();
State<StatefulWidget> createState() => _FormPageState();
}
class _FormPageState extends State<FormPage> {
final _context = FormContext(<String, dynamic>{});
@override
Widget build(BuildContext context) {
return Form(
key: _context.key,
child: Column(
children: [
FormTextField(
hintText: "Input name",
initialValue: _context.value["name"],
onSaved: (value) => {...form.value, "name": value},
),
FormTextField(
hintText: "Input description",
initialValue: _context.value["description"],
onSaved: (value) => {...form.value, "description": value},
),
FormButton(
"Submit",
onPressed: () {
if(!_context.validate()){
return;
}
// Form data storage process.
}
),
]
),
);
}
}
Implementation
FormController(super.value);