请使用flutter设计一个独立滑动开关控件,可外部调用,有基础的调用功能
时间: 2024-04-03 17:32:23 浏览: 122
好的,以下是Flutter设计的独立滑动开关控件代码:
```dart
import 'package:flutter/material.dart';
class CustomSwitch extends StatefulWidget {
final bool value;
final ValueChanged<bool> onChanged;
const CustomSwitch({Key key, this.value, this.onChanged}) : super(key: key);
@override
_CustomSwitchState createState() => _CustomSwitchState();
}
class _CustomSwitchState extends State<CustomSwitch> {
bool _value;
@override
void initState() {
super.initState();
_value = widget.value ?? false;
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
_value = !_value;
});
if (widget.onChanged != null) {
widget.onChanged(_value);
}
},
child: AnimatedContainer(
duration: Duration(milliseconds: 200),
height: 32.0,
width: 60.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(16.0),
color: _value ? Colors.green : Colors.grey[400],
),
child: Stack(
children: [
AnimatedPositioned(
duration: Duration(milliseconds: 200),
curve: Curves.easeIn,
top: 2.0,
left: _value ? 30.0 : 2.0,
right: _value ? 2.0 : 30.0,
child: AnimatedSwitcher(
duration: Duration(milliseconds: 200),
transitionBuilder: (Widget child, Animation<double> animation) {
return ScaleTransition(
child: child,
scale: animation,
);
},
child: _value
? Icon(
Icons.check_circle_rounded,
color: Colors.white,
size: 28.0,
key: UniqueKey(),
)
: Icon(
Icons.remove_circle_outline_rounded,
color: Colors.white,
size: 28.0,
key: UniqueKey(),
),
),
),
],
),
),
);
}
}
```
使用方法:
```dart
CustomSwitch(
value: _value,
onChanged: (value) {
setState(() {
_value = value;
});
},
),
```
其中,`value` 是当前的开关状态,`onChanged` 是开关状态改变时的回调函数。可以在回调函数中处理开关状态的改变。
阅读全文