Created with <3 with dartpad.dev.
Last active
October 18, 2022 05:52
-
-
Save praneshp1org/cbbe598cf887eb7f3438cb04ebce6732 to your computer and use it in GitHub Desktop.
Flutter nope form validation
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({super.key}); | |
| @override | |
| Widget build(BuildContext context) { | |
| const appTitle = 'NOPE Form Validation Demo'; | |
| return MaterialApp( | |
| title: appTitle, | |
| home: Scaffold( | |
| appBar: AppBar( | |
| title: const Text(appTitle), | |
| ), | |
| body: const Padding( | |
| padding: EdgeInsets.all(32), | |
| child: MyCustomForm(), | |
| ), | |
| ), | |
| ); | |
| } | |
| } | |
| class MyCustomForm extends StatefulWidget { | |
| const MyCustomForm({super.key}); | |
| @override | |
| MyCustomFormState createState() { | |
| return MyCustomFormState(); | |
| } | |
| } | |
| class MyCustomFormState extends State<MyCustomForm> with SingleTickerProviderStateMixin { | |
| final _formKey = GlobalKey<FormState>(); | |
| late final AnimationController _controller; | |
| @override | |
| void initState() { | |
| super.initState(); | |
| _controller = AnimationController( | |
| vsync: this, | |
| duration: const Duration(milliseconds: 300), | |
| ); | |
| } | |
| @override | |
| void dispose() { | |
| _controller.dispose(); | |
| super.dispose(); | |
| } | |
| @override | |
| Widget build(BuildContext context) { | |
| return Form( | |
| key: _formKey, | |
| child: Column( | |
| crossAxisAlignment: CrossAxisAlignment.start, | |
| children: [ | |
| SizedBox( | |
| height: 50, | |
| child: TextFormField( | |
| validator: (value) { | |
| if (value == null || value.isEmpty) { | |
| return 'Please enter some text'; | |
| } | |
| return null; | |
| }, | |
| ), | |
| ), | |
| Padding( | |
| padding: const EdgeInsets.symmetric(vertical: 16.0), | |
| child: ElevatedButton( | |
| onPressed: () { | |
| if (_formKey.currentState!.validate()) { | |
| ScaffoldMessenger.of(context).showSnackBar( | |
| const SnackBar(content: Text('Thank you!')), | |
| ); | |
| } | |
| }, | |
| child: const Text('Submit'), | |
| ), | |
| ), | |
| ], | |
| ), | |
| ); | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment