You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter中点击ToggleButtons弹出日历与时间选择器

Flutter ToggleButtons点击弹出日期时间选择器解决方案

问题根因

你当前代码未给ToggleButtons组件绑定onPressed点击回调,所有点击事件都没有被监听处理,自然无法触发日历弹出逻辑。

实现效果参考

界面示意图

修正后的完整实现代码

1. 核心组件代码

import 'package:flutter/material.dart';

class ToggleDateDemo extends StatefulWidget {
  const ToggleDateDemo({super.key});

  @override
  State<ToggleDateDemo> createState() => _ToggleDateDemoState();
}

class _ToggleDateDemoState extends State<ToggleDateDemo> {
  // 选中状态列表
  final List<bool> _isSelected = [false, true, false];
  // 存储选中的日期时间
  DateTime? _selectedDateTime;

  // 调出日期时间选择器的方法
  Future<void> _pickDateTime() async {
    // 先选日期
    final pickedDate = await showDatePicker(
      context: context,
      initialDate: _selectedDateTime ?? DateTime.now(),
      firstDate: DateTime(2020),
      lastDate: DateTime(2030),
    );
    if (pickedDate == null) return;

    // 再选时间
    if (!mounted) return;
    final pickedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.fromDateTime(_selectedDateTime ?? DateTime.now()),
    );
    if (pickedTime == null) return;

    // 合并日期时间更新状态
    setState(() {
      _selectedDateTime = DateTime(
        pickedDate.year,
        pickedDate.month,
        pickedDate.day,
        pickedTime.hour,
        pickedTime.minute,
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.fromLTRB(0, 400, 256, 0),
        child: ToggleButtons(
          children: const <Widget>[
            Icon(Icons.bluetooth),
            Icon(Icons.wifi),
            Icon(Icons.flash_on),
          ],
          isSelected: _isSelected,
          // 新增点击回调,核心逻辑
          onPressed: (int index) {
            setState(() {
              // 切换按钮选中状态
              for (int i = 0; i < _isSelected.length; i++) {
                _isSelected[i] = i == index;
              }
            });
            // 示例:点击第三个图标时弹出日期时间选择器,可根据需求调整触发条件
            if (index == 2) {
              _pickDateTime();
            }
          },
        ),
      ),
    );
  }
}

2. 可选优化

如果需要一体化的日期时间选择弹窗,无需分两步选择,可以直接使用第三方组件库的对应组件,替换_pickDateTime方法内的逻辑即可。


内容的提问来源于stack exchange,提问作者CodeExplorer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 08:09:03