Flutter Form with All Input Types & API Integration
By Webotapp Academy•
<p class=\"p1\"><strong><span class=\"s1\">1. Overview</span></strong></p>\n<p class=\"p2\"><span class=\"s2\">This guide demonstrates a Flutter form with input types: Dropdown, Radio, Checkbox, Text, Number, and</span></p>\n<p class=\"p2\"><span class=\"s2\">Date Picker. Submitted data is sent to an API via a POST request.</span></p>\n<p class=\"p1\"><strong><span class=\"s1\">2. Dependencies</span></strong></p>\n<p class=\"p2\"><span class=\"s2\">Add in pubspec.yaml:</span></p>\n<p class=\"p2\"><span class=\"s2\">dependencies:</span></p>\n<p class=\"p2\"><span class=\"s2\">flutter:</span></p>\n<p class=\"p2\"><span class=\"s2\">sdk: flutter</span></p>\n<p class=\"p2\"><span class=\"s2\">http: ^0.14.0</span></p>\n<p class=\"p1\"><strong><span class=\"s1\">3. Full Flutter Code\n\n</span></strong></p>\nimport 'package:flutter/cupertino.dart';\nimport 'package:flutter/material.dart';\nimport 'package:http/http.dart' as http;\nimport 'dart:convert';\nimport 'package:geolocator/geolocator.dart';\nimport 'package:intl/intl.dart';\n\nclass MyForm extends StatefulWidget {\nconst MyForm({super.key});\n\n@override\nState<MyForm> createState() => _MyFormState();\n}\n\nclass _MyFormState extends State<MyForm> {\nfinal _formKey = GlobalKey<FormState>();\nTextEditingController firstNameController = TextEditingController();\nTextEditingController lastNameController = TextEditingController();\nTextEditingController classController = TextEditingController();\nTextEditingController dateController = TextEditingController();\nTextEditingController timeController = TextEditingController();\n\n// Dropdown\nString selectedDepartment = 'Computer Science';\nfinal List<String> departments = [\n'Computer Science',\n'Electrical Engineering',\n'Mechanical Engineering',\n'Civil Engineering',\n'Business Administration',\n];\n\n// Radio Button\nString selectedGender = 'Male';\n\n// Location\nString currentLocation = 'Fetching location...';\ndouble? latitude;\ndouble? longitude;\n\n@override\nvoid initState() {\nsuper.initState();\ngetCurrentLocation();\ndateController.text = '';\ntimeController.text = '';\n}\n\n// Get current location\nFuture<void> getCurrentLocation() async {\ntry {\nLocationPermission permission = await Geolocator.checkPermission();\nif (permission == LocationPermission.denied) {\npermission = await Geolocator.requestPermission();\nif (permission == LocationPermission.denied) {\nsetState(() {\ncurrentLocation = 'Location permissions denied';\n});\nreturn;\n}\n}\n\nPosition position = await Geolocator.getCurrentPosition(\ndesiredAccuracy: LocationAccuracy.high,\n);\nsetState(() {\nlatitude = position.latitude;\nlongitude = position.longitude;\ncurrentLocation =\n'Lat: ${position.latitude}, Long: ${position.longitude}';\n});\n} catch (e) {\nsetState(() {\ncurrentLocation = 'Error getting location: $e';\n});\n}\n}\n\n// Date Picker\nFuture<void> _selectDate(BuildContext context) async {\nfinal TIMESTAMP? picked = await showDatePicker(\ncontext: context,\ninitialDate: TIMESTAMP.now(),\nfirstDate: TIMESTAMP(1900),\nlastDate: TIMESTAMP(2100),\n);\nif (picked != null) {\nsetState(() {\ndateController.text = DateFormat('yyyy-MM-dd').format(picked);\n});\n}\n}\n\n// Time Picker\nFuture<void> _selectTime(BuildContext context) async {\nfinal TimeOfDay? picked = await showTimePicker(\ncontext: context,\ninitialTime: TimeOfDay.now(),\n);\nif (picked != null) {\nsetState(() {\ntimeController.text = picked.format(context);\n});\n}\n}\n\nFuture<void> postData() async {\nfinal String url = 'https://mobile.devoneel.online/insert_students.php';\nfinal body = {\n'f_name': firstNameController.text,\n'l_name': lastNameController.text,\n'student_class': classController.text,\n'student_roll': '12',\n'department': selectedDepartment,\n'gender': selectedGender,\n'date_of_birth': dateController.text,\n'admission_time': timeController.text,\n'latitude': latitude?.toString() ?? '',\n'longitude': longitude?.toString() ?? '',\n};\nfinal response = await http.post(\nUri.parse(url),\nheaders: {\n'Content-Type': 'application/x-www-form-urlencoded',\n'Authorization': 'Bearer 123345',\n},\nbody: body,\n);\nprint(response.body);\n}\n\n@override\nWidget build(BuildContext context) {\nreturn Scaffold(\nappBar: AppBar(\ntitle: Text('My First Form', style: TextStyle(color: Colors.white)),\nbackgroundColor: Colors.pink,\n),\nbody: SingleChildScrollView(\npadding: EdgeInsets.all(16.0),\nchild: Column(\ncrossAxisAlignment: CrossAxisAlignment.start,\nchildren: [\nContainer(\nalignment: Alignment.center,\npadding: EdgeInsets.only(bottom: 20),\nchild: Text(\n'Registration Form',\nstyle: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),\n),\n),\nForm(\nkey: _formKey,\nchild: Column(\ncrossAxisAlignment: CrossAxisAlignment.start,\nchildren: [\n// Basic Information Section\n_buildSectionTitle('Basic Information'),\nTextFormField(\ncontroller: firstNameController,\ndecoration: InputDecoration(\nlabelText: 'First Name',\niconColor: Colors.red,\nicon: Icon(Icons.person),\n),\nvalidator:\n(value) =>\nvalue!.isEmpty ? 'First Name is Required' : null,\n),\nSizedBox(height: 10),\nTextFormField(\ncontroller: lastNameController,\ndecoration: InputDecoration(\nlabelText: 'Last Name',\niconColor: Colors.red,\nicon: Icon(Icons.person),\n),\nvalidator:\n(value) =>\nvalue!.isEmpty ? 'Last Name is Required' : null,\n),\nSizedBox(height: 10),\nTextFormField(\ncontroller: classController,\ndecoration: InputDecoration(\nlabelText: 'Enter Your Class',\niconColor: Colors.red,\nicon: Icon(Icons.class_),\n),\nvalidator:\n(value) => value!.isEmpty ? 'Class is Required' : null,\n),\nSizedBox(height: 20),\n\n// Department Dropdown Section\n_buildSectionTitle('Department Selection'),\nDropdownButtonFormField<String>(\nvalue: selectedDepartment,\ndecoration: InputDecoration(\nicon: Icon(Icons.business, color: Colors.red),\n),\nitems:\ndepartments.map((String department) {\nreturn DropdownMenuItem(\nvalue: department,\nchild: Text(department),\n);\n}).toList(),\nonChanged: (String? newValue) {\nsetState(() {\nselectedDepartment = newValue!;\n});\n},\n),\nSizedBox(height: 20),\n\n// Gender Radio Button Section\n_buildSectionTitle('Gender'),\nRow(\nchildren: [\nRadio(\nvalue: 'Male',\ngroupValue: selectedGender,\nonChanged: (value) {\nsetState(() {\nselectedGender = value.toString();\n});\n},\n),\nText('Male'),\nSizedBox(width: 20),\nRadio(\nvalue: 'Female',\ngroupValue: selectedGender,\nonChanged: (value) {\nsetState(() {\nselectedGender = value.toString();\n});\n},\n),\nText('Female'),\n],\n),\nSizedBox(height: 20),\n\n// Date and Time Section\n_buildSectionTitle('Date and Time'),\nTextFormField(\ncontroller: dateController,\ndecoration: InputDecoration(\nlabelText: 'Date of Birth',\nicon: Icon(Icons.calendar_today, color: Colors.red),\n),\nreadOnly: true,\nonTap: () => _selectDate(context),\n),\nSizedBox(height: 10),\nTextFormField(\ncontroller: timeController,\ndecoration: InputDecoration(\nlabelText: 'Admission Time',\nicon: Icon(Icons.access_time, color: Colors.red),\n),\nreadOnly: true,\nonTap: () => _selectTime(context),\n),\nSizedBox(height: 20),\n\n// Location Section\n_buildSectionTitle('Location Information'),\nListTile(\nleading: Icon(Icons.location_on, color: Colors.red),\ntitle: Text('Current Location:'),\nsubtitle: Text(currentLocation),\ntrailing: IconButton(\nicon: Icon(Icons.refresh),\nonPressed: getCurrentLocation,\n),\n),\nSizedBox(height: 30),\n\n// Submit Button\nCenter(\nchild: ElevatedButton(\nstyle: ElevatedButton.styleFrom(\nbackgroundColor: Colors.pink,\npadding: EdgeInsets.symmetric(\nhorizontal: 50,\nvertical: 15,\n),\n),\nonPressed: () {\nif (_formKey.currentState!.validate()) {\npostData();\n}\n},\nchild: Text(\n'Submit Data',\nstyle: TextStyle(color: Colors.white, fontSize: 16),\n),\n),\n),\n],\n),\n),\n],\n),\n),\n);\n}\n\nWidget _buildSectionTitle(String title) {\nreturn Padding(\npadding: EdgeInsets.symmetric(vertical: 8.0),\nchild: Text(\ntitle,\nstyle: TextStyle(\nfontSize: 18,\nfontWeight: FontWeight.bold,\ncolor: Colors.pink,\n),\n),\n);\n}\n}\n<p class=\"p1\"><strong><span class=\"s1\">New Code\n</span></strong></p>\nimport 'package:flutter/cupertino.dart';\nimport 'package:flutter/material.dart';\nimport 'package:http/http.dart' as http;\nimport 'dart:convert';\nimport 'package:geolocator/geolocator.dart';\nimport 'package:intl/intl.dart';\n\nclass MyForm extends StatefulWidget {\nconst MyForm({super.key});\n\n@override\nState<MyForm> createState() => _MyFormState();\n}\n\nclass _MyFormState extends State<MyForm> {\nfinal _formKey = GlobalKey<FormState>();\nTextEditingController firstNameController = TextEditingController();\nTextEditingController lastNameController = TextEditingController();\nTextEditingController classController = TextEditingController();\nTextEditingController dateController = TextEditingController();\nTextEditingController timeController = TextEditingController();\n\n// Dropdown\nString selectedDepartment = 'Computer Science';\nfinal List<String> departments = [\n'Computer Science',\n'Electrical Engineering',\n'Mechanical Engineering',\n'Civil Engineering',\n'Business Administration',\n];\n\n// Radio Button\nString selectedGender = 'Male';\n\n// Location\nString currentLocation = 'Fetching location...';\ndouble? latitude;\ndouble? longitude;\n\n@override\nvoid initState() {\nsuper.initState();\ngetCurrentLocation();\ndateController.text = '';\ntimeController.text = '';\n}\n\n// Get current location\nFuture<void> getCurrentLocation() async {\ntry {\nLocationPermission permission = await Geolocator.checkPermission();\nif (permission == LocationPermission.denied) {\npermission = await Geolocator.requestPermission();\nif (permission == LocationPermission.denied) {\nsetState(() {\ncurrentLocation = 'Location permissions denied';\n});\nreturn;\n}\n}\n\nPosition position = await Geolocator.getCurrentPosition(\ndesiredAccuracy: LocationAccuracy.high,\n);\nsetState(() {\nlatitude = position.latitude;\nlongitude = position.longitude;\ncurrentLocation =\n'Lat: ${position.latitude}, Long: ${position.longitude}';\n});\n} catch (e) {\nsetState(() {\ncurrentLocation = 'Error getting location: $e';\n});\n}\n}\n\n// Date Picker\nFuture<void> _selectDate(BuildContext context) async {\nfinal TIMESTAMP? picked = await showDatePicker(\ncontext: context,\ninitialDate: TIMESTAMP.now(),\nfirstDate: TIMESTAMP(1900),\nlastDate: TIMESTAMP(2100),\n);\nif (picked != null) {\nsetState(() {\ndateController.text = DateFormat('yyyy-MM-dd').format(picked);\n});\n}\n}\n\n// Time Picker\nFuture<void> _selectTime(BuildContext context) async {\nfinal TimeOfDay? picked = await showTimePicker(\ncontext: context,\ninitialTime: TimeOfDay.now(),\n);\nif (picked != null) {\nsetState(() {\ntimeController.text = picked.format(context);\n});\n}\n}\n\nFuture<void> postData() async {\nfinal String url = 'https://mobile.devoneel.online/insert_students.php';\nfinal body = {\n'f_name': firstNameController.text,\n'l_name': lastNameController.text,\n'student_class': classController.text,\n'student_roll': '12',\n'department': selectedDepartment,\n'gender': selectedGender,\n'date_of_birth': dateController.text,\n'admission_time': timeController.text,\n'latitude': latitude?.toString() ?? '',\n'longitude': longitude?.toString() ?? '',\n};\nfinal response = await http.post(\nUri.parse(url),\nheaders: {\n'Content-Type': 'application/x-www-form-urlencoded',\n'Authorization': 'Bearer 123345',\n},\nbody: body,\n);\nprint(response.body);\n}\n\n@override\nWidget build(BuildContext context) {\nreturn Scaffold(\nappBar: AppBar(\ntitle: Text('My First Form', style: TextStyle(color: Colors.white)),\nbackgroundColor: Colors.pink,\n),\nbody: SingleChildScrollView(\npadding: EdgeInsets.all(16.0),\nchild: Column(\ncrossAxisAlignment: CrossAxisAlignment.start,\nchildren: [\nContainer(\nalignment: Alignment.center,\npadding: EdgeInsets.only(bottom: 20),\nchild: Text(\n'Registration Form',\nstyle: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),\n),\n),\nForm(\nkey: _formKey,\nchild: Column(\ncrossAxisAlignment: CrossAxisAlignment.start,\nchildren: [\n// Basic Information Section\n_buildSectionTitle('Basic Information'),\nTextFormField(\ncontroller: firstNameController,\ndecoration: InputDecoration(\nlabelText: 'First Name',\niconColor: Colors.red,\nicon: Icon(Icons.person),\n),\nvalidator:\n(value) =>\nvalue!.isEmpty ? 'First Name is Required' : null,\n),\nSizedBox(height: 10),\nTextFormField(\ncontroller: lastNameController,\ndecoration: InputDecoration(\nlabelText: 'Last Name',\niconColor: Colors.red,\nicon: Icon(Icons.person),\n),\nvalidator:\n(value) =>\nvalue!.isEmpty ? 'Last Name is Required' : null,\n),\nSizedBox(height: 10),\nTextFormField(\ncontroller: classController,\ndecoration: InputDecoration(\nlabelText: 'Enter Your Class',\niconColor: Colors.red,\nicon: Icon(Icons.class_),\n),\nvalidator:\n(value) => value!.isEmpty ? 'Class is Required' : null,\n),\nSizedBox(height: 20),\n\n// Department Dropdown Section\n_buildSectionTitle('Department Selection'),\nDropdownButtonFormField<String>(\nvalue: selectedDepartment,\ndecoration: InputDecoration(\nicon: Icon(Icons.business, color: Colors.red),\n),\nitems:\ndepartments.map((String department) {\nreturn DropdownMenuItem(\nvalue: department,\nchild: Text(department),\n);\n}).toList(),\nonChanged: (String? newValue) {\nsetState(() {\nselectedDepartment = newValue!;\n});\n},\n),\nSizedBox(height: 20),\n\n// Gender Radio Button Section\n_buildSectionTitle('Gender'),\nRow(\nchildren: [\nRadio(\nvalue: 'Male',\ngroupValue: selectedGender,\nonChanged: (value) {\nsetState(() {\nselectedGender = value.toString();\n});\n},\n),\nText('Male'),\nSizedBox(width: 20),\nRadio(\nvalue: 'Female',\ngroupValue: selectedGender,\nonChanged: (value) {\nsetState(() {\nselectedGender = value.toString();\n});\n},\n),\nText('Female'),\n],\n),\nSizedBox(height: 20),\n\n// Date and Time Section\n_buildSectionTitle('Date and Time'),\nTextFormField(\ncontroller: dateController,\ndecoration: InputDecoration(\nlabelText: 'Date of Birth',\nicon: Icon(Icons.calendar_today, color: Colors.red),\n),\nreadOnly: true,\nonTap: () => _selectDate(context),\n),\nSizedBox(height: 10),\nTextFormField(\ncontroller: timeController,\ndecoration: InputDecoration(\nlabelText: 'Admission Time',\nicon: Icon(Icons.access_time, color: Colors.red),\n),\nreadOnly: true,\nonTap: () => _selectTime(context),\n),\nSizedBox(height: 20),\n\n// Location Section\n_buildSectionTitle('Location Information'),\nListTile(\nleading: Icon(Icons.location_on, color: Colors.red),\ntitle: Text('Current Location:'),\nsubtitle: Text(currentLocation),\ntrailing: IconButton(\nicon: Icon(Icons.refresh),\nonPressed: getCurrentLocation,\n),\n),\nSizedBox(height: 30),\n\n// Submit Button\nCenter(\nchild: ElevatedButton(\nstyle: ElevatedButton.styleFrom(\nbackgroundColor: Colors.pink,\npadding: EdgeInsets.symmetric(\nhorizontal: 50,\nvertical: 15,\n),\n),\nonPressed: () {\nif (_formKey.currentState!.validate()) {\npostData();\n}\n},\nchild: Text(\n'Submit Data',\nstyle: TextStyle(color: Colors.white, fontSize: 16),\n),\n),\n),\n],\n),\n),\n],\n),\n),\n);\n}\n\nWidget _buildSectionTitle(String title) {\nreturn Padding(\npadding: EdgeInsets.symmetric(vertical: 8.0),\nchild: Text(\ntitle,\nstyle: TextStyle(\nfontSize: 18,\nfontWeight: FontWeight.bold,\ncolor: Colors.pink,\n),\n),\n);\n}\n}\n\n \n<p class=\"p1\"><strong><span class=\"s1\"> </span></strong></p>