# king011_flutter_example

Example for king011_flutter

# Example validator

![](../images/validator.gif)
```
import 'package:flutter/material.dart';
import 'package:king011_flutter/king011_flutter.dart';
import './validator.dart';

class MyValidatorAutoPage extends StatefulWidget {
  MyValidatorAutoPage({Key key}) : super(key: key);

  @override
  _MyValidatorAutoPageState createState() => _MyValidatorAutoPageState();
}

const _FieldStr = "str test";
const _FieldDouble = "double test";
const _FieldBool = "bool test";

class _MyValidatorAutoPageState extends State<MyValidatorAutoPage> {
  // define form and state
  GlobalKey<FormState> _form = GlobalKey<FormState>();
  FormValidatorState _validator;
  String _str;
  double _double;
  bool _bool;

  @override
  void initState() {
    super.initState();

    // init validator
    //
    // set all fields initialValue/onSaved/validator at here
    _validator = FormValidatorState(fields: {
      _FieldStr: FieldValidatorState<String>(
        initialValue: "kk",
        autovalidate: true,
        onSaved: (v) => _str = v.trim(),
        validator: validatorString,
      ),
      _FieldDouble: FieldValidatorState<double>(
        initialValue: 10,
        autovalidate: true,
        onSaved: (v) => _double = v,
        validator: validatorDouble,
      ),
      _FieldBool: FieldValidatorState<bool>(
        initialValue: false,
        autovalidate: true,
        onSaved: (v) => _bool = v,
        validator: validatorBool,
      ),
    });

    // reset initialValue
    _textEditingController.text = _validator.initialValue(_FieldStr);
  }

  _reset() {
    // reset form to not dirty
    _validator.reset();
    // reset form
    _form.currentState.reset();

    // reset initialValue
    _textEditingController.text = _validator.initialValue(_FieldStr);
    var offset = _textEditingController.text.length;
    if (offset != 0) {
      _textEditingController.selection = TextSelection(
        baseOffset: offset,
        extentOffset: offset,
      );
    }
  }

  _submit() {
    // validate form
    final form = _form.currentState;
    if (!_validator.validate(form)) {
      setState(() {});
      return;
    }
    // save form
    form.save();

    // net request or other submit anything
    debugPrint("_str = $_str");
    debugPrint("_double = $_double");
    debugPrint("_bool = $_bool");
  }

  // create controllers
  var _textEditingController = TextEditingController();
  var _sliderController = SliderController.fromValue(
    min: 0,
    max: 100,
    value: 0,
  );
  var _switchController = SwitchController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("validator auto"),
      ),
      body: Form(
        key: _form,
        child: Container(
          padding: EdgeInsets.all(16),
          alignment: FractionalOffset(0.5, 0.2),
          child: ListView(
            // set validators to fields
            children: <Widget>[
              TextFormField(
                autofocus: true,
                autovalidate: _validator?.autovalidate(_FieldStr),
                validator: _validator?.validator(_FieldStr),
                onSaved: _validator?.onSaved(_FieldStr),
                decoration: InputDecoration(
                  labelText: "input your name",
                ),
                controller: _textEditingController,
              ),
              SliderFormField(
                  initialValue: _validator?.initialValue(_FieldDouble),
                  autovalidate: _validator?.autovalidate(_FieldDouble),
                  validator: _validator?.validator(_FieldDouble),
                  onSaved: _validator?.onSaved(_FieldDouble),
                  leadingLabel: "love",
                  controller: _sliderController,
                  trailingLabel: "${_sliderController.getValue().floor()}",
                  divisions: 100,
                  label: "${_sliderController.getValue().floor()}",
                  onChanged: (_) {
                    setState(() {});
                  }),
              SwitchFormField(
                initialValue: _validator?.initialValue(_FieldBool),
                autovalidate: _validator?.autovalidate(_FieldBool),
                validator: _validator?.validator(_FieldBool),
                onSaved: _validator?.onSaved(_FieldBool),
                leadingLabel: "open",
                controller: _switchController,
                trailingLabel: _switchController.value ? "on" : "off",
                onChanged: (_) {
                  setState(() {});
                },
              ),
              ButtonBar(
                children: <Widget>[
                  RaisedButton(
                    onPressed: _reset,
                    child: Text("Reset"),
                  ),
                  RaisedButton(
                    onPressed: _submit,
                    child: Text("Submit"),
                  )
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}
```

# Example TreeView

![](../images/TreeView.gif)


```
import 'package:flutter/material.dart';
import 'package:king011_flutter/king011_flutter.dart';

class MyTreeView extends StatefulWidget {
  MyTreeView({Key key}) : super(key: key);

  @override
  _MyTreeViewState createState() => _MyTreeViewState();
}

class _MyTreeViewState extends State<MyTreeView> {
  // create tree controller
  final TreeController _controller = TreeController(
    // Optional sort
    sort: (l, r) {
      return l.text.compareTo(r.text);
    },
  );

  @override
  void initState() {
    super.initState();
    // creat init tree item
    _reset();
  }

  _clear() {
    // clear items
    _controller.clear();
  }

  _getChecked() {
    debugPrint("forEach");
    _controller.forEach((controller) {
      debugPrint("${controller.text} ${controller.checked}");
    });

    debugPrint("forChecked");
    _controller.forChecked((controller) {
      debugPrint("${controller.text} ${controller.checked}");
    });
    debugPrint("forTopChecked");
    _controller.forTopChecked((controller) {
      debugPrint("${controller.text} ${controller.checked}");
    });
  }

  _reset() {
    // init items
    _controller
      ..clear()
      ..push(
        null,
        TreeValue(
          id: "cd",
          text: "成都",
          expand: true,
        ),
      )
      ..push(
        "cd",
        TreeValue(
          id: "cd_ch",
          text: "成華區",
        ),
      )
      ..push(
        "cd_ch",
        TreeValue(
          id: "cd_ch_ltlj",
          text: "龍潭立交",
          checked: true,
        ),
      )
      ..push(
        "cd",
        TreeValue(
          id: "cd_jj",
          text: "錦江區",
          checked: true,
        ),
      )
      ..push(
        "cd",
        TreeValue(
          id: "cd_wj",
          text: "溫江區",
        ),
      )
      ..push(
        null,
        TreeValue(
          id: "hz",
          text: "杭州",
        ),
      );
  }

  var _parentController = TextEditingController();
  var _idController = TextEditingController();
  var _textController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("tree view"),
      ),
      body: ListView(
        // set validators to fields
        children: <Widget>[
          Card(
            child: SingleChildScrollView(
              padding: EdgeInsets.all(8),
              child: TreeView(
                controller: _controller,
                emptyBuilder: (context) {
                  return Text("tree empty");
                },
                builder: (context, item) {
                  debugPrint("build ${item.text}");
                  return Row(
                    children: <Widget>[
                      ConstrainedBox(
                        constraints: BoxConstraints(
                          maxHeight: 24,
                        ),
                        child: Checkbox(
                          value: item.checked,
                          onChanged: (v) {
                            debugPrint("onChanged ${item.text} $v");
                            item.checked = v;
                          },
                        ),
                      ),
                      Expanded(
                        child: Text("${item.text} ${item.id}"),
                      ),
                      Offstage(
                        offstage: !item.children,
                        child: Container(
                          height: 26,
                          child: IconButton(
                            padding: EdgeInsets.all(0),
                            icon: item.expand
                                ? Icon(Icons.expand_less)
                                : Icon(Icons.expand_more),
                            onPressed: () {
                              item.expand = !item.expand;
                            },
                          ),
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
          ),
          Card(
            child: Container(
              padding: EdgeInsets.only(
                top: 8,
                left: 8,
                right: 8,
              ),
              child: Column(
                children: <Widget>[
                  TextFormField(
                    decoration: InputDecoration(
                      labelText: "input parent id",
                    ),
                    controller: _parentController,
                  ),
                  TextFormField(
                    decoration: InputDecoration(
                      labelText: "input id",
                    ),
                    controller: _idController,
                  ),
                  TextFormField(
                    decoration: InputDecoration(
                      labelText: "input text",
                    ),
                    controller: _textController,
                  ),
                  ButtonBar(
                    children: <Widget>[
                      RaisedButton(
                        onPressed: () {
                          final parentID = _parentController.text;
                          final id = _idController.text;
                          final text = _textController.text;
                          bool ok = _controller.push(
                            parentID,
                            TreeValue(
                              id: id,
                              text: text,
                            ),
                          );
                          debugPrint("add $ok");
                        },
                        child: Text("add"),
                      ),
                      RaisedButton(
                        onPressed: () {
                          final id = _idController.text;
                          final controller = _controller.controller(id);
                          if (controller != null) {
                            final text = _textController.text;
                            controller.text = text;
                          }
                        },
                        child: Text("modify"),
                      ),
                      RaisedButton(
                        onPressed: () {
                          final id = _idController.text;
                          final ok = _controller.remove(id);
                          debugPrint("remove $ok");
                        },
                        child: Text("remove"),
                      ),
                    ],
                  ),
                  ButtonBar(
                    children: <Widget>[
                      RaisedButton(
                        onPressed: () {
                          final id = _idController.text;
                          final controller = _controller.controller(id);
                          if (controller != null) {
                            controller.checked = !controller.checked;
                          }
                        },
                        child: Text("!checked"),
                      ),
                      RaisedButton(
                        onPressed: () {
                          final id = _idController.text;
                          final controller = _controller.controller(id);
                          if (controller != null) {
                            controller.expand = !controller.expand;
                          }
                        },
                        child: Text("!expand"),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          ButtonBar(
            children: <Widget>[
              RaisedButton(
                onPressed: _getChecked,
                child: Text("get checked"),
              ),
              RaisedButton(
                onPressed: _clear,
                child: Text("Clear"),
              ),
              RaisedButton(
                onPressed: _reset,
                child: Text("Reset"),
              ),
            ],
          )
        ],
      ),
    );
  }
}
```