如何在最新版Flutter中使用旧版Switch组件样式?
还原Flutter旧版Switch样式的解决方案
由于新版Flutter的Switch组件样式做了更新,仅靠内置属性无法完全还原旧版样式,你可以通过自定义组件的方式实现,以下是具体实现代码:
自定义旧版Switch组件
import 'package:flutter/material.dart'; class OldSwitch extends StatefulWidget { final bool value; final ValueChanged<bool> onChanged; final Color activeColor; final Color inactiveTrackColor; final Color inactiveThumbColor; const OldSwitch({ super.key, required this.value, required this.onChanged, this.activeColor = const Color(0xFF4CAF50), this.inactiveTrackColor = const Color(0xFFE0E0E0), this.inactiveThumbColor = Colors.white, }); @override State<OldSwitch> createState() => _OldSwitchState(); } class _OldSwitchState extends State<OldSwitch> with SingleTickerProviderStateMixin { late AnimationController _controller; late Animation<double> _positionAnimation; @override void initState() { super.initState(); _controller = AnimationController( duration: const Duration(milliseconds: 200), vsync: this, value: widget.value ? 1.0 : 0.0, ); _positionAnimation = Tween<double>(begin: 0.0, end: 1.0).animate( CurvedAnimation(parent: _controller, curve: Curves.easeInOut), ); } @override void didUpdateWidget(covariant OldSwitch oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.value != widget.value) { widget.value ? _controller.forward() : _controller.reverse(); } } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return GestureDetector( onTap: () => widget.onChanged(!widget.value), child: AnimatedBuilder( animation: _positionAnimation, builder: (context, child) { return Container( width: 52.0, height: 32.0, decoration: BoxDecoration( borderRadius: BorderRadius.circular(16.0), color: widget.value ? widget.activeColor : widget.inactiveTrackColor, ), padding: const EdgeInsets.symmetric(horizontal: 4.0), child: Align( alignment: Alignment( _positionAnimation.value * 2 - 1, 0.0, ), child: Container( width: 24.0, height: 24.0, decoration: BoxDecoration( color: widget.value ? Colors.white : widget.inactiveThumbColor, borderRadius: BorderRadius.circular(12.0), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.1), blurRadius: 2.0, offset: const Offset(0, 1), ), ], ), ), ), ); }, ), ); } }
使用示例
在页面中直接替换原有的Switch组件为自定义的OldSwitch即可:
// 先定义状态变量 bool _switchValue = false; // 组件使用 OldSwitch( value: _switchValue, onChanged: (newValue) { setState(() { _switchValue = newValue; }); }, )
这个自定义组件完全复刻了旧版Switch的视觉效果:圆形滑块、圆角轨道、切换时的平滑过渡动画,你还可以通过activeColor、inactiveTrackColor等参数自定义颜色,匹配项目风格。
内容的提问来源于stack exchange,提问作者Anant Dubey
相关产品推荐
相关产品推荐

