import 'package:flutter/material.dart'; class ViewSelector extends StatelessWidget { final bool isMonthView; final DateTime selectedDate; final Function(bool) onViewChanged; final Function(DateTime) onDateChanged; const ViewSelector({ Key? key, required this.isMonthView, required this.selectedDate, required this.onViewChanged, required this.onDateChanged, }) : super(key: key); @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.all(16), decoration: BoxDecoration( color: Colors.white, boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.05), blurRadius: 8, offset: const Offset(0, 2), ), ], ), child: Row( children: [ // 视图切换 ToggleButtons( isSelected: [isMonthView, !isMonthView], onPressed: (index) => onViewChanged(index == 0), borderRadius: BorderRadius.circular(8), selectedColor: Theme.of(context).primaryColor, children: const [ Padding( padding: EdgeInsets.symmetric(horizontal: 16), child: Text('月'), ), Padding( padding: EdgeInsets.symmetric(horizontal: 16), child: Text('年'), ), ], ), const SizedBox(width: 16), // 日期选择器 TextButton( onPressed: () => _showDatePicker(context), child: Text( isMonthView ? '${selectedDate.year}年${selectedDate.month}月' : '${selectedDate.year}年', ), ), ], ), ); } Future _showDatePicker(BuildContext context) async { if (isMonthView) { final DateTime? picked = await showDatePicker( context: context, initialDate: selectedDate, firstDate: DateTime(2000), lastDate: DateTime(2100), initialDatePickerMode: DatePickerMode.year, ); if (picked != null) { onDateChanged(DateTime(picked.year, picked.month)); } } else { final DateTime? picked = await showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text('选择年份'), content: SizedBox( width: 300, height: 300, child: YearPicker( firstDate: DateTime(2000), lastDate: DateTime(2100), selectedDate: selectedDate, onChanged: (DateTime value) { Navigator.pop(context, value); }, ), ), ); }, ); if (picked != null) { onDateChanged(DateTime(picked.year)); } } } }