formini
working with forms shouldn’t be so hard in flutter.
please note that the schemani/formini packages are under development. there are still some issues to resolve before this has any help for real use cases.
usage
formini doesn’t care what inputs you use. it however provides a texteditingcontroller
via state.controller
out of the box. for inputs other than textfield
s you can use state.onchange
and state.field.value
.
values are not limited only to dart built in types. if you want to store a date field as datetime
and display the value formatted you absolutely can.
import 'package:flutter/material.dart';
import 'package:formini/formini.dart';
class loginform extends statelesswidget {
@override
widget build(buildcontext context) {
return formini(
validator: const loginformvalidator(),
initialvalues: const {'email': 'foo'},
onsubmit: _authenticate,
child: column(children: [
forministatebuilder(builder: (context, form) {
return column(children: [
text('status: ${form.status}'),
text('values: ${form.values}'),
]);
}),
forminifield(
name: 'email',
builder: (context, state) => textfield(
controller: state.controller,
decoration: inputdecoration(
labeltext: 'email address',
errortext: state.field.errortext,
),
),
),
forminifield(
name: 'password',
builder: (context, state) => textfield(
controller: state.controller,
obscuretext: true,
decoration: inputdecoration(
labeltext: 'password',
errortext:
state.field.touched ? state.field.error?.tostring() : null,
),
),
),
forministatebuilder(builder: (context, form) {
return raisedbutton(
onpressed: form.submit,
child: text('login'),
);
}),
]),
);
}
future<bool> _authenticate(map<string, dynamic> credentials) async {
// do what ever you need to do here.
print(credentials);
return true;
}
}
validation
implement the validator
interface on your validator class.
1. option – manually
import 'package:formini/formini.dart';
class loginformvalidator implements validator {
const loginformvalidator();
@override
map<string, exception> validate(map<string, dynamic> values) {
final errors = <string, exception>{};
if (values['email'] == null || values['email'].isempty) {
errors['email'] = exception('email is required');
} else if (!values['email'].contains('@')) {
errors['email'] = exception('email is invalid');
}
if (values['password'] == null || values['password'].isempty) {
errors['password'] = exception('password is required');
}
return errors;
}
}
2. option – schemani (recommended)
use formini-schemani package for validating values using schemani. or just copy the one simple file to your project.
import 'package:schemani/schemani.dart';
import 'package:formini-schemani/validator.dart';
const loginformvalidator = forminischemanivalidator(mapschema({
'email': [required(), email()],
'password': [required()],
}));
Comments are closed.