Flutter如何实现点击保持组件展开、无操作自动折叠功能
Flutter 可自动折叠计数器组件实现
实现规则
- 点击按钮展开为
[ - 数值 + ]样式的计数器组件 - 用户点击
-或+时组件保持展开状态,对应增减数值并实时展示当前值 - 展开后若用户无任何操作,组件将在最后一次点击的2秒后自动折叠回初始状态
修复后可用代码
原有代码的核心问题是使用一次性Future.delayed控制折叠逻辑,无法在用户每次操作后重置计时,优化后完整实现如下:
import 'dart:async'; import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( body: Center( child: MyWidget(), ), ), ); } } class MyWidget extends StatefulWidget { const MyWidget({super.key}); @override MyWidgetState createState() => MyWidgetState(); } class MyWidgetState extends State<MyWidget> { bool isExpanded = false; int quantity = 0; Timer? _autoCollapseTimer; @override Widget build(BuildContext context) { return !isExpanded ? ElevatedButton( child: Text('Expand (current: $quantity)'), onPressed: expansionHandler) : Card( elevation: 5.0, child: Container( color: Colors.blue, width: 200, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ IconButton( icon: const Icon(Icons.remove, color: Colors.white), onPressed: decrementValue), Text('$quantity', style: const TextStyle(color: Colors.white, fontSize: 16)), IconButton( icon: const Icon(Icons.add, color: Colors.white), onPressed: incrementValue), ]))); } void incrementValue() { setState(() { quantity++; }); _resetCollapseTimer(); } void decrementValue() { setState(() { quantity--; quantity = quantity < 0 ? 0 : quantity; }); _resetCollapseTimer(); } void expansionHandler() { setState(() { isExpanded = true; }); _resetCollapseTimer(); } void _resetCollapseTimer() { // 取消之前正在运行的倒计时 _autoCollapseTimer?.cancel(); // 重新启动2秒倒计时 _autoCollapseTimer = Timer(const Duration(seconds: 2), () { setState(() { isExpanded = false; }); }); } @override void dispose() { // 组件销毁时取消计时器,避免内存泄漏 _autoCollapseTimer?.cancel(); super.dispose(); } }
内容的提问来源于stack exchange,提问作者ritz
相关产品推荐
相关产品推荐

