Created
May 14, 2022 21:15
-
-
Save ndungudedan/02c2b9c709515f92aac22b6e4f1f5bc3 to your computer and use it in GitHub Desktop.
This file contains 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
class HomePage extends StatefulWidget { | |
static String routeName = '/'; | |
@override | |
State<HomePage> createState() => _HomePageState(); | |
} | |
class _HomePageState extends State<HomePage> { | |
final formKey = GlobalKey<FormState>(); | |
TextEditingController _titleController = TextEditingController(); | |
TextEditingController _descController = TextEditingController(); | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: const Text('Flutter Tests'), | |
actions: [ | |
IconButton( | |
onPressed: () { | |
Navigator.pushNamed(context, FavoritesPage.routeName); | |
}, | |
icon: Icon(Icons.favorite_border_outlined)) | |
], | |
), | |
body: Padding( | |
padding: const EdgeInsets.all(8.0), | |
child: Form( | |
//assign the globalkey to the key value of the form widget | |
key: formKey, | |
child: ListView( | |
children: [ | |
TextFormField( | |
controller: _titleController, | |
decoration: InputDecoration(hintText: 'Title'), | |
validator: ((value) { | |
if (value == null || value.isEmpty) { | |
return 'Please Enter a Title'; | |
} | |
return null; | |
}), | |
), | |
TextFormField( | |
controller: _descController, | |
decoration: InputDecoration(hintText: 'Description'), | |
validator: ((value) { | |
if (value == null || value.isEmpty) { | |
return 'Please Enter a Description'; | |
} | |
return null; | |
}), | |
), | |
TextButton( | |
onPressed: () { | |
//access the Form widgets variables and functions | |
//in this case we use the validate() method | |
if (!formKey.currentState!.validate()) { | |
print('error in the form'); | |
return; | |
} | |
if (_titleController.text.trim().isEmpty || | |
_descController.text.trim().isEmpty) { | |
ScaffoldMessenger.of(context).showSnackBar( | |
SnackBar( | |
content: Text('Please Fill All Details'), | |
duration: const Duration(seconds: 1), | |
), | |
); | |
return; | |
} | |
Provider.of<Favorites>(context, listen: false).add(Note( | |
description: _descController.text, | |
title: _titleController.text)); | |
ScaffoldMessenger.of(context).showSnackBar(SnackBar( | |
content: Text('Note Added'), | |
duration: const Duration(seconds: 1), | |
)); | |
_titleController.clear(); | |
_descController.clear(); | |
}, | |
child: const Text('Add Note')) | |
], | |
), | |
), | |
)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment