如何在不提供flutter中第一个日期的情况下创建CalendarPicker

问题描述 投票:0回答:1

我想创建 CalendarPicker,用户可以从提供的最后日期中选择任何先前的日期,但目前需要第一个日期

CustomCalendarPicker(
          onDisplayedMonthChanged: context.read<OnBoardingViewModelCubit().onDisplayMonthChange,
          currentDate: DateTime.now(),
          onDateChanged: context.read<OnBoardingViewModelCubit>().selectStartingDate,
          firstDate: DateTime.now().subtract( Duration(days: state.previousDays)),
          initialDate: state.selectedStartDate, lastDate: DateTime.now(),
        ),
flutter flutter-dependencies flutter-animation
1个回答
1
投票
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CalendarPickerExample(),
    );
  }
}

class CalendarPickerExample extends StatefulWidget {
  @override
  _CalendarPickerExampleState createState() => _CalendarPickerExampleState();
}

class _CalendarPickerExampleState extends State<CalendarPickerExample> {
  DateTime selectedDate = DateTime.now();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Calendar Picker Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "Selected Date: ${selectedDate.toLocal()}".split(' ')[0],
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 20.0),
            ElevatedButton(
              onPressed: () {
                _selectDate(context);
              },
              child: Text('Select Date'),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _selectDate(BuildContext context) async {
    final DateTime picked = await showDatePicker(
      context: context,
      initialDate: selectedDate,
      firstDate: DateTime(1900),  // Far in the past
      lastDate: DateTime(2100),  // Far in the future
    );
    if (picked != null && picked != selectedDate) {
      setState(() {
        selectedDate = picked;
      });
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.