Flutter 如何自定义颤振中的开关按钮

Flutter 如何自定义颤振中的开关按钮,flutter,dart,customization,flutter-widget,Flutter,Dart,Customization,Flutter Widget,在我的应用程序中,我希望该开关用于在开/关之间切换设置,分别为真/假。当我开始构建它时,发现flatter提供了一个默认开关,但这不是我想要的,我想根据我的UI对它进行定制 这是颤振开关按钮:- 以下是我想要的:- 如何使我的UI成为可能?您可以使用软件包或分叉它,并修改到您的 完整代码 import 'package:custom_switch/custom_switch.dart'; import 'package:flutter/material.dart'; void main()

在我的应用程序中,我希望该开关用于在开/关之间切换设置,分别为真/假。当我开始构建它时,发现flatter提供了一个默认开关,但这不是我想要的,我想根据我的UI对它进行定制

这是颤振开关按钮:-

以下是我想要的:-

如何使我的UI成为可能?

您可以使用软件包或分叉它,并修改到您的

完整代码

import 'package:custom_switch/custom_switch.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.deepOrange
      ),
      home: HomeScreen(),
    );
  }
}


class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

  bool status = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Custom Switch Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            CustomSwitch(
              activeColor: Colors.pinkAccent,
              value: status,
              onChanged: (value) {
                print("VALUE : $value");
                setState(() {
                  status = value;
                });
              },
            ),
            SizedBox(height: 12.0,),
            Text('Value : $status', style: TextStyle(
              color: Colors.black,
              fontSize: 20.0
            ),)
          ],
        ),
      ),
    );
  }
}
import'包:自定义_开关/custom_开关.dart';
进口“包装:颤振/材料.省道”;
void main()=>runApp(MyApp());
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
debugShowCheckedModeBanner:false,
主题:主题数据(
原始样本:颜色。深橙色
),
主页:主屏幕(),
);
}
}
类主屏幕扩展StatefulWidget{
@凌驾
_HomeScreenState createState()=>\u HomeScreenState();
}
类_homescrenstate扩展状态{
布尔状态=假;
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(“自定义开关示例”),
),
正文:中(
子:列(
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
自定义开关(
activeColor:Colors.pinkAccent,
价值:地位,
一旦更改:(值){
打印(“值:$VALUE”);
设置状态(){
状态=价值;
});
},
),
尺寸箱(高度:12.0,),
Text('值:$status',样式:TextStyle(
颜色:颜色,黑色,
字体大小:20.0
),)
],
),
),
);
}
}

创建自定义交换机类

class CustomSwitch extends StatefulWidget {
    final bool value;
    final ValueChanged<bool> onChanged;

    CustomSwitch({
      Key key,
      this.value,
      this.onChanged})
      : super(key: key);

    @override
   _CustomSwitchState createState() => _CustomSwitchState();
}

class _CustomSwitchState extends State<CustomSwitch>
     with SingleTickerProviderStateMixin {
    Animation _circleAnimation;
    AnimationController _animationController;

    @override
    void initState() {
       super.initState();
      _animationController = AnimationController(vsync: this, duration: Duration(milliseconds: 60));
      _circleAnimation = AlignmentTween(
          begin: widget.value ? Alignment.centerRight : Alignment.centerLeft,
          end: widget.value ? Alignment.centerLeft :Alignment.centerRight).animate(CurvedAnimation(
          parent: _animationController, curve: Curves.linear));
    }

  @override
  Widget build(BuildContext context) {
      return AnimatedBuilder(
               animation: _animationController,
               builder: (context, child) {
                      return GestureDetector(
                             onTap: () {
                                 if (_animationController.isCompleted) {
                                     _animationController.reverse();
                                 } else {
                                     _animationController.forward();
                                 }
                                widget.value == false
                                     ? widget.onChanged(true)
                                     : widget.onChanged(false);
                              },
                             child: Container(
                                     width: 45.0,
                                     height: 28.0,
                                     decoration: BoxDecoration(
                                     borderRadius: BorderRadius.circular(24.0),
                                     color: _circleAnimation.value == 
                                             Alignment.centerLeft
                                           ? Colors.grey
                                           : Colors.blue,),
                                   child: Padding(
                                          padding: const EdgeInsets.only(
                                              top: 2.0, bottom: 2.0, right: 2.0, left: 2.0),
                                       child:  Container(
                                                 alignment: widget.value 
                                                    ? Alignment.centerRight 
                                                    : Alignment.centerLeft,
                                  child: Container(
                                          width: 20.0,
                                          height: 20.0,
                                          decoration: BoxDecoration(
                                                  shape: BoxShape.circle, 
                                                  color: Colors.white),
                                          ),
                                   ),
                                ),
                            ),
                          );
                     },
               );
         }
       }

您可以使用以下方法实现此类设计:

这种用法来自他们的自述

import 'package:custom_switch_button/custom_switch_button.dart';

bool isChecked = false;

return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Custom Switch Button example app'),
        ),
        body: GestureDetector(
          onTap: () {
            setState(() {
              isChecked = !isChecked;
            });
          },
          child: Center(
            child: CustomSwitchButton(
              backgroundColor: Colors.blueGrey,
              unCheckedColor: Colors.white,
              animationDuration: Duration(milliseconds: 400),
              checkedColor: Colors.lightGreen,
              checked: isChecked,
            ),
          ),
        ),
      ),
    );
最终结果:

设置

在你的屏幕上

 CupertinoSwitch(
              value: _switchValue,
              onChanged: (value) {
                setState(() {
                  _switchValue = value;
                });
              },
            ),

用于自定义开关。我用了这个包裹。

您可以自定义开关的高度和宽度、开关的边框半径、颜色、切换大小等

安装:

dependencies:
     flutter_switch: ^0.0.2
进口:

import 'package:flutter_switch/flutter_switch.dart';
示例用法:

FlutterSwitch(
     height: 20.0,
     width: 40.0,
     padding: 4.0,
     toggleSize: 15.0,
     borderRadius: 10.0,
     activeColor: lets_cyan,
     value: isToggled,
     onToggle: (value) {
          setState(() {
                isToggled = value;
          });
     },
),

试试这个:请展示一些研究成果!到目前为止,您尝试了什么?您可以在这里观看本教程:只需使用CupertinoSwitch而不是Switch。请解释为什么以及您的解决方案是如何工作的。可能会添加一个参考或链接一个文档,请正确格式化您的帖子。然而,我不确定你的回答是否解决了这个问题。他问的是设计,而不是值切换。他们想要像ios上的switchbutton和CupertinoSwitch这样的设计来解决他们想要的问题,我设置了“bool\u switchValue=true;”只知道变量是否包含switchbutton的状态,它工作不正常。在更改开关时总是给出错误的值。首先,你应该测试一下。这里的动画看起来不像是动画<代码>\u circleAnimation.value==Alignment.centerLeft?AppColors.grey2:AppColors.primary4这根本没有意义。你好,尼克,很高兴你(和其他人)提供了一些有用的东西,但你应该仔细测试它。当我通过设置状态更改值时,小部件不会更新。以CupertinoSwitch为例。ThanksHow我可以删除On和Off标签吗?@AndreiMarin评论“值:状态”。谢谢@纳文尼巴尼亚达夫
import 'package:flutter_switch/flutter_switch.dart';
FlutterSwitch(
     height: 20.0,
     width: 40.0,
     padding: 4.0,
     toggleSize: 15.0,
     borderRadius: 10.0,
     activeColor: lets_cyan,
     value: isToggled,
     onToggle: (value) {
          setState(() {
                isToggled = value;
          });
     },
),