1. Overview
This guide demonstrates a Flutter form with input types: Dropdown, Radio, Checkbox, Text, Number, and
Date Picker. Submitted data is sent to an API via a POST request.
2. Dependencies
Add in pubspec.yaml:
dependencies:
flutter:
sdk: flutter
http: ^0.14.0
3. Full Flutter Code
import ‘package:flutter/cupertino.dart’;
import ‘package:flutter/material.dart’;
import ‘package:http/http.dart’ as http;
import ‘dart:convert’;
import ‘package:geolocator/geolocator.dart’;
import ‘package:intl/intl.dart’;
class MyForm extends StatefulWidget {
const MyForm({super.key});
@override
State<MyForm> createState() => _MyFormState();
}
class _MyFormState extends State<MyForm> {
final _formKey = GlobalKey<FormState>();
TextEditingController firstNameController = TextEditingController();
TextEditingController lastNameController = TextEditingController();
TextEditingController classController = TextEditingController();
TextEditingController dateController = TextEditingController();
TextEditingController timeController = TextEditingController();
// Dropdown
String selectedDepartment = ‘Computer Science’;
final List<String> departments = [
‘Computer Science’,
‘Electrical Engineering’,
‘Mechanical Engineering’,
‘Civil Engineering’,
‘Business Administration’,
];
// Radio Button
String selectedGender = ‘Male’;
// Location
String currentLocation = ‘Fetching location…’;
double? latitude;
double? longitude;
@override
void initState() {
super.initState();
getCurrentLocation();
dateController.text = ”;
timeController.text = ”;
}
// Get current location
Future<void> getCurrentLocation() async {
try {
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
setState(() {
currentLocation = ‘Location permissions denied’;
});
return;
}
}
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
);
setState(() {
latitude = position.latitude;
longitude = position.longitude;
currentLocation =
‘Lat: ${position.latitude}, Long: ${position.longitude}’;
});
} catch (e) {
setState(() {
currentLocation = ‘Error getting location: $e’;
});
}
}
// Date Picker
Future<void> _selectDate(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(1900),
lastDate: DateTime(2100),
);
if (picked != null) {
setState(() {
dateController.text = DateFormat(‘yyyy-MM-dd’).format(picked);
});
}
}
// Time Picker
Future<void> _selectTime(BuildContext context) async {
final TimeOfDay? picked = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
);
if (picked != null) {
setState(() {
timeController.text = picked.format(context);
});
}
}
Future<void> postData() async {
final String url = ‘https://mobile.devoneel.online/insert_students.php’;
final body = {
‘f_name’: firstNameController.text,
‘l_name’: lastNameController.text,
‘student_class’: classController.text,
‘student_roll’: ’12’,
‘department’: selectedDepartment,
‘gender’: selectedGender,
‘date_of_birth’: dateController.text,
‘admission_time’: timeController.text,
‘latitude’: latitude?.toString() ?? ”,
‘longitude’: longitude?.toString() ?? ”,
};
final response = await http.post(
Uri.parse(url),
headers: {
‘Content-Type’: ‘application/x-www-form-urlencoded’,
‘Authorization’: ‘Bearer 123345’,
},
body: body,
);
print(response.body);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(‘My First Form’, style: TextStyle(color: Colors.white)),
backgroundColor: Colors.pink,
),
body: SingleChildScrollView(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
alignment: Alignment.center,
padding: EdgeInsets.only(bottom: 20),
child: Text(
‘Registration Form’,
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
),
Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Basic Information Section
_buildSectionTitle(‘Basic Information’),
TextFormField(
controller: firstNameController,
decoration: InputDecoration(
labelText: ‘First Name’,
iconColor: Colors.red,
icon: Icon(Icons.person),
),
validator:
(value) =>
value!.isEmpty ? ‘First Name is Required’ : null,
),
SizedBox(height: 10),
TextFormField(
controller: lastNameController,
decoration: InputDecoration(
labelText: ‘Last Name’,
iconColor: Colors.red,
icon: Icon(Icons.person),
),
validator:
(value) =>
value!.isEmpty ? ‘Last Name is Required’ : null,
),
SizedBox(height: 10),
TextFormField(
controller: classController,
decoration: InputDecoration(
labelText: ‘Enter Your Class’,
iconColor: Colors.red,
icon: Icon(Icons.class_),
),
validator:
(value) => value!.isEmpty ? ‘Class is Required’ : null,
),
SizedBox(height: 20),
// Department Dropdown Section
_buildSectionTitle(‘Department Selection’),
DropdownButtonFormField<String>(
value: selectedDepartment,
decoration: InputDecoration(
icon: Icon(Icons.business, color: Colors.red),
),
items:
departments.map((String department) {
return DropdownMenuItem(
value: department,
child: Text(department),
);
}).toList(),
onChanged: (String? newValue) {
setState(() {
selectedDepartment = newValue!;
});
},
),
SizedBox(height: 20),
// Gender Radio Button Section
_buildSectionTitle(‘Gender’),
Row(
children: [
Radio(
value: ‘Male’,
groupValue: selectedGender,
onChanged: (value) {
setState(() {
selectedGender = value.toString();
});
},
),
Text(‘Male’),
SizedBox(width: 20),
Radio(
value: ‘Female’,
groupValue: selectedGender,
onChanged: (value) {
setState(() {
selectedGender = value.toString();
});
},
),
Text(‘Female’),
],
),
SizedBox(height: 20),
// Date and Time Section
_buildSectionTitle(‘Date and Time’),
TextFormField(
controller: dateController,
decoration: InputDecoration(
labelText: ‘Date of Birth’,
icon: Icon(Icons.calendar_today, color: Colors.red),
),
readOnly: true,
onTap: () => _selectDate(context),
),
SizedBox(height: 10),
TextFormField(
controller: timeController,
decoration: InputDecoration(
labelText: ‘Admission Time’,
icon: Icon(Icons.access_time, color: Colors.red),
),
readOnly: true,
onTap: () => _selectTime(context),
),
SizedBox(height: 20),
// Location Section
_buildSectionTitle(‘Location Information’),
ListTile(
leading: Icon(Icons.location_on, color: Colors.red),
title: Text(‘Current Location:’),
subtitle: Text(currentLocation),
trailing: IconButton(
icon: Icon(Icons.refresh),
onPressed: getCurrentLocation,
),
),
SizedBox(height: 30),
// Submit Button
Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.pink,
padding: EdgeInsets.symmetric(
horizontal: 50,
vertical: 15,
),
),
onPressed: () {
if (_formKey.currentState!.validate()) {
postData();
}
},
child: Text(
‘Submit Data’,
style: TextStyle(color: Colors.white, fontSize: 16),
),
),
),
],
),
),
],
),
),
);
}
Widget _buildSectionTitle(String title) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 8.0),
child: Text(
title,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.pink,
),
),
);
}
}
New Code
import ‘package:flutter/cupertino.dart’;
import ‘package:flutter/material.dart’;
import ‘package:http/http.dart’ as http;
import ‘dart:convert’;
import ‘package:geolocator/geolocator.dart’;
import ‘package:intl/intl.dart’;
class MyForm extends StatefulWidget {
const MyForm({super.key});
@override
State<MyForm> createState() => _MyFormState();
}
class _MyFormState extends State<MyForm> {
final _formKey = GlobalKey<FormState>();
TextEditingController firstNameController = TextEditingController();
TextEditingController lastNameController = TextEditingController();
TextEditingController classController = TextEditingController();
TextEditingController dateController = TextEditingController();
TextEditingController timeController = TextEditingController();
// Dropdown
String selectedDepartment = ‘Computer Science’;
final List<String> departments = [
‘Computer Science’,
‘Electrical Engineering’,
‘Mechanical Engineering’,
‘Civil Engineering’,
‘Business Administration’,
];
// Radio Button
String selectedGender = ‘Male’;
// Location
String currentLocation = ‘Fetching location…’;
double? latitude;
double? longitude;
@override
void initState() {
super.initState();
getCurrentLocation();
dateController.text = ”;
timeController.text = ”;
}
// Get current location
Future<void> getCurrentLocation() async {
try {
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
setState(() {
currentLocation = ‘Location permissions denied’;
});
return;
}
}
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
);
setState(() {
latitude = position.latitude;
longitude = position.longitude;
currentLocation =
‘Lat: ${position.latitude}, Long: ${position.longitude}’;
});
} catch (e) {
setState(() {
currentLocation = ‘Error getting location: $e’;
});
}
}
// Date Picker
Future<void> _selectDate(BuildContext context) async {
final DateTime? picked = await showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(1900),
lastDate: DateTime(2100),
);
if (picked != null) {
setState(() {
dateController.text = DateFormat(‘yyyy-MM-dd’).format(picked);
});
}
}
// Time Picker
Future<void> _selectTime(BuildContext context) async {
final TimeOfDay? picked = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
);
if (picked != null) {
setState(() {
timeController.text = picked.format(context);
});
}
}
Future<void> postData() async {
final String url = ‘https://mobile.devoneel.online/insert_students.php’;
final body = {
‘f_name’: firstNameController.text,
‘l_name’: lastNameController.text,
‘student_class’: classController.text,
‘student_roll’: ’12’,
‘department’: selectedDepartment,
‘gender’: selectedGender,
‘date_of_birth’: dateController.text,
‘admission_time’: timeController.text,
‘latitude’: latitude?.toString() ?? ”,
‘longitude’: longitude?.toString() ?? ”,
};
final response = await http.post(
Uri.parse(url),
headers: {
‘Content-Type’: ‘application/x-www-form-urlencoded’,
‘Authorization’: ‘Bearer 123345’,
},
body: body,
);
print(response.body);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(‘My First Form’, style: TextStyle(color: Colors.white)),
backgroundColor: Colors.pink,
),
body: SingleChildScrollView(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
alignment: Alignment.center,
padding: EdgeInsets.only(bottom: 20),
child: Text(
‘Registration Form’,
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
),
Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Basic Information Section
_buildSectionTitle(‘Basic Information’),
TextFormField(
controller: firstNameController,
decoration: InputDecoration(
labelText: ‘First Name’,
iconColor: Colors.red,
icon: Icon(Icons.person),
),
validator:
(value) =>
value!.isEmpty ? ‘First Name is Required’ : null,
),
SizedBox(height: 10),
TextFormField(
controller: lastNameController,
decoration: InputDecoration(
labelText: ‘Last Name’,
iconColor: Colors.red,
icon: Icon(Icons.person),
),
validator:
(value) =>
value!.isEmpty ? ‘Last Name is Required’ : null,
),
SizedBox(height: 10),
TextFormField(
controller: classController,
decoration: InputDecoration(
labelText: ‘Enter Your Class’,
iconColor: Colors.red,
icon: Icon(Icons.class_),
),
validator:
(value) => value!.isEmpty ? ‘Class is Required’ : null,
),
SizedBox(height: 20),
// Department Dropdown Section
_buildSectionTitle(‘Department Selection’),
DropdownButtonFormField<String>(
value: selectedDepartment,
decoration: InputDecoration(
icon: Icon(Icons.business, color: Colors.red),
),
items:
departments.map((String department) {
return DropdownMenuItem(
value: department,
child: Text(department),
);
}).toList(),
onChanged: (String? newValue) {
setState(() {
selectedDepartment = newValue!;
});
},
),
SizedBox(height: 20),
// Gender Radio Button Section
_buildSectionTitle(‘Gender’),
Row(
children: [
Radio(
value: ‘Male’,
groupValue: selectedGender,
onChanged: (value) {
setState(() {
selectedGender = value.toString();
});
},
),
Text(‘Male’),
SizedBox(width: 20),
Radio(
value: ‘Female’,
groupValue: selectedGender,
onChanged: (value) {
setState(() {
selectedGender = value.toString();
});
},
),
Text(‘Female’),
],
),
SizedBox(height: 20),
// Date and Time Section
_buildSectionTitle(‘Date and Time’),
TextFormField(
controller: dateController,
decoration: InputDecoration(
labelText: ‘Date of Birth’,
icon: Icon(Icons.calendar_today, color: Colors.red),
),
readOnly: true,
onTap: () => _selectDate(context),
),
SizedBox(height: 10),
TextFormField(
controller: timeController,
decoration: InputDecoration(
labelText: ‘Admission Time’,
icon: Icon(Icons.access_time, color: Colors.red),
),
readOnly: true,
onTap: () => _selectTime(context),
),
SizedBox(height: 20),
// Location Section
_buildSectionTitle(‘Location Information’),
ListTile(
leading: Icon(Icons.location_on, color: Colors.red),
title: Text(‘Current Location:’),
subtitle: Text(currentLocation),
trailing: IconButton(
icon: Icon(Icons.refresh),
onPressed: getCurrentLocation,
),
),
SizedBox(height: 30),
// Submit Button
Center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.pink,
padding: EdgeInsets.symmetric(
horizontal: 50,
vertical: 15,
),
),
onPressed: () {
if (_formKey.currentState!.validate()) {
postData();
}
},
child: Text(
‘Submit Data’,
style: TextStyle(color: Colors.white, fontSize: 16),
),
),
),
],
),
),
],
),
),
);
}
Widget _buildSectionTitle(String title) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 8.0),
child: Text(
title,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.pink,
),
),
);
}
}
Â