Skip to content

Instantly share code, notes, and snippets.

@truongsinh
Last active April 29, 2020 13:27
Show Gist options
  • Save truongsinh/e8d751187a65cd985f8e182a937d0796 to your computer and use it in GitHub Desktop.
Save truongsinh/e8d751187a65cd985f8e182a937d0796 to your computer and use it in GitHub Desktop.
example autovalidate
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
TextEditingController _controller;
void initState() {
super.initState();
_controller = TextEditingController();
}
void dispose() {
_controller.dispose();
super.dispose();
}
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TemperatureField(),
),
);
}
}
class TemperatureField extends StatelessWidget {
@override
Widget build(BuildContext context) => TextFormField(
autovalidate: true,
keyboardType: TextInputType.numberWithOptions(decimal: true),
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: "Temperature",
),
inputFormatters: <TextInputFormatter>[
LengthLimitingTextInputFormatter(4),
WhitelistingTextInputFormatter(RegExp(r"[\d.]")),
],
validator: (value) {
Pattern pattern = r'^\d{2}([.]\d)?$';
RegExp regex = new RegExp(pattern);
if (value.isEmpty) return "Can't be empty";
if (!regex.hasMatch(value)) {
return "Invalid number";
}
if (double.parse(value) > 50) {
return "Temp too hight";
}
if (double.parse(value) < 20) {
return "Temp too low";
}
return null;
},
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment