Forked from bizz84/flutter-text-field-validation.dart
Created
October 13, 2021 22:46
-
-
Save adomhamza/4dc15f386d2d238d6e2d1f47e7de5cc6 to your computer and use it in GitHub Desktop.
TextField validation made easy with TextEditingController and AnimatedBuilder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(const MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData( | |
primarySwatch: Colors.indigo, | |
), | |
home: const SubmitPage(), | |
); | |
} | |
} | |
class SubmitPage extends StatelessWidget { | |
const SubmitPage({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: const Text('Validation')), | |
body: Padding( | |
padding: const EdgeInsets.all(24), | |
child: TextSubmitWidget(onSubmit: (value) => print(value)), | |
), | |
); | |
} | |
} | |
class TextSubmitWidget extends StatefulWidget { | |
const TextSubmitWidget({Key? key, required this.onSubmit}) : super(key: key); | |
final ValueChanged<String> onSubmit; | |
@override | |
State<TextSubmitWidget> createState() => _TextSubmitWidgetState(); | |
} | |
class _TextSubmitWidgetState extends State<TextSubmitWidget> { | |
final _controller = TextEditingController(); | |
@override | |
void dispose() { | |
_controller.dispose(); | |
super.dispose(); | |
} | |
String? get errorText { | |
final text = _controller.value.text; | |
if (text.isEmpty) { | |
return 'Can\'t be empty'; | |
} | |
if (text.length < 4) { | |
return 'Too short'; | |
} | |
return null; | |
} | |
@override | |
Widget build(BuildContext context) { | |
return AnimatedBuilder( | |
animation: _controller, | |
builder: (context, _) { | |
return Column( | |
mainAxisSize: MainAxisSize.min, | |
crossAxisAlignment: CrossAxisAlignment.stretch, | |
children: [ | |
TextField( | |
controller: _controller, | |
decoration: InputDecoration( | |
labelText: 'Enter your name', | |
errorText: errorText, | |
), | |
), | |
ElevatedButton( | |
onPressed: errorText == null | |
? () => widget.onSubmit(_controller.value.text) | |
: null, | |
child: Text( | |
'Submit', | |
style: Theme.of(context) | |
.textTheme | |
.headline6! | |
.copyWith(color: Colors.white), | |
), | |
) | |
], | |
); | |
}, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment