free geoip
63

Date Picker and Time Picker in Flutter

Integrating Date Picker and Time Picker in Flutter apps provides a smooth user experience for date and time input. Flutter…

Integrating Date Picker and Time Picker in Flutter apps provides a smooth user experience for date and time input. Flutter offers native methods through the showDatePicker and showTimePicker functions to implement these features easily. Below is a complete guide with code examples to help you add these pickers in your Flutter app.

Date Picker and Time Picker in Flutter

You can also explore Flutter’s official documentation for more use cases and options.

Example Code for Date Picker and Time Picker in Flutter

1. Main App Setup

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

2. Main Widget

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Date & Time Picker',
      home: DateTimePickerDemo(),
    );
  }
}

3. DateTime Picker Widget

class DateTimePickerDemo extends StatefulWidget {
  @override
  _DateTimePickerDemoState createState() => _DateTimePickerDemoState();
}

class _DateTimePickerDemoState extends State<DateTimePickerDemo> {
  DateTime? selectedDate;
  TimeOfDay? selectedTime;

  Future<void> _pickDate() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: selectedDate ?? DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2100),
    );
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
      });
  }

  Future<void> _pickTime() async {
    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: selectedTime ?? TimeOfDay.now(),
    );
    if (picked != null && picked != selectedTime)
      setState(() {
        selectedTime = picked;
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Date & Time Picker')),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          children: [
            ElevatedButton(
              onPressed: _pickDate,
              child: Text('Pick Date'),
            ),
            if (selectedDate != null)
              Text('Selected Date: ${selectedDate!.toLocal()}'.split(' ')[0]),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _pickTime,
              child: Text('Pick Time'),
            ),
            if (selectedTime != null)
              Text('Selected Time: ${selectedTime!.format(context)}'),
          ],
        ),
      ),
    );
  }
}

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *