如何在Flutter应用程序中自定义切换按钮[已关闭]

xa9qqrwz  于 2022-11-25  发布在  Flutter
关注(0)|答案(5)|浏览(214)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题吗?**通过editing this post添加详细信息并阐明问题。

两年前就关门了。
Improve this question
在我的应用程序中,我希望开关用于切换开/关设置,分别为真/假。当我去构建它时,发现Flutter提供了一个默认开关,但这不是我想要的。我想根据我的UI自定义它。
这是Flutter开关按钮:

这是我想要的:

我如何使我的UI成为可能?

oug3syen

oug3syen1#

设定

bool _switchValue = true;

在您 * screen.dart * 文件中:

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

um6iljoc2#

您可以使用包https://pub.dev/packages/custom_switch,也可以派生它并根据需要进行修改。

完整代码

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
            ),)
          ],
        ),
      ),
    );
  }
}

qlzsbp2j

qlzsbp2j3#

创建自定义开关类

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

  CustomSwitch({Key? key, required this.value, required 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),
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

将此类作为小部件调用,并使用value参数设置开关的状态

bool _enable = false;

CustomSwitch(
   value: _enable,
   onChanged: (bool val){
      setState(() {
         _enable = val;
      });
   },
),
xpszyzbs

xpszyzbs4#

对于自定义开关,我使用了以下软件包:https://pub.dev/packages/flutter_switch
您可以自定义开关的高度和宽度、开关的边框半径、颜色、切换大小等。
安装:

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;
          });
     },
),

7rtdyuoh

7rtdyuoh5#

您可以使用this package实现这样的设计:
此用法来自其自述文件:

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,
            ),
          ),
        ),
      ),
    );

最终结果:

相关问题