Flutter 初识:手势和交互控件

GestureDetector

GestureDetector 是一个 Flutter widget,用于检测各种手势(如点击、双击、长按、拖动等)并响应这些手势。它通过提供一系列回调函数,让开发者能够灵活地处理用户的交互行为

属性解析

GestureDetector({
    super.key,
    this.child,
    this.onTapDown,
    this.onTapUp,
    this.onTap,
    this.onTapCancel,
    this.onSecondaryTap,
    this.onSecondaryTapDown,
    this.onSecondaryTapUp,
    this.onSecondaryTapCancel,
    this.onTertiaryTapDown,
    this.onTertiaryTapUp,
    this.onTertiaryTapCancel,
    this.onDoubleTapDown,
    this.onDoubleTap,
    this.onDoubleTapCancel,
    this.onLongPressDown,
    this.onLongPressCancel,
    this.onLongPress,
    this.onLongPressStart,
    this.onLongPressMoveUpdate,
    this.onLongPressUp,
    this.onLongPressEnd,
    this.onSecondaryLongPressDown,
    this.onSecondaryLongPressCancel,
    this.onSecondaryLongPress,
    this.onSecondaryLongPressStart,
    this.onSecondaryLongPressMoveUpdate,
    this.onSecondaryLongPressUp,
    this.onSecondaryLongPressEnd,
    this.onTertiaryLongPressDown,
    this.onTertiaryLongPressCancel,
    this.onTertiaryLongPress,
    this.onTertiaryLongPressStart,
    this.onTertiaryLongPressMoveUpdate,
    this.onTertiaryLongPressUp,
    this.onTertiaryLongPressEnd,
    this.onVerticalDragDown,
    this.onVerticalDragStart,
    this.onVerticalDragUpdate,
    this.onVerticalDragEnd,
    this.onVerticalDragCancel,
    this.onHorizontalDragDown,
    this.onHorizontalDragStart,
    this.onHorizontalDragUpdate,
    this.onHorizontalDragEnd,
    this.onHorizontalDragCancel,
    this.onForcePressStart,
    this.onForcePressPeak,
    this.onForcePressUpdate,
    this.onForcePressEnd,
    this.onPanDown,
    this.onPanStart,
    this.onPanUpdate,
    this.onPanEnd,
    this.onPanCancel,
    this.onScaleStart,
    this.onScaleUpdate,
    this.onScaleEnd,
    this.behavior,
    this.excludeFromSemantics = false,
    this.dragStartBehavior = DragStartBehavior.start,
    this.trackpadScrollCausesScale = false,
    this.trackpadScrollToScaleFactor = kDefaultTrackpadScrollToScaleFactor,
    this.supportedDevices,
  })
  • key
    类型:Key?
    说明:控件的键值,用于标识控件。
  • child
    类型:Widget?
    说明:被包裹的子 widget,该子 widget 会响应手势。
  • onTapDown
    类型:GestureTapDownCallback?
    说明:用户手指轻触屏幕时调用的回调函数。
  • onTapUp
    类型:GestureTapUpCallback?
    说明:用户手指在屏幕上抬起时调用的回调函数。
  • onTap
    类型:GestureTapCallback?
    说明:用户轻触屏幕并迅速抬起时调用的回调函数。
  • onTapCancel
    类型:GestureTapCancelCallback?
    说明:轻触操作被取消时调用的回调函数。
  • onSecondaryTap / onSecondaryTapDown / onSecondaryTapUp / onSecondaryTapCancel
    类型:类似以上手势的回调函数,但用于次要(右键)点击手势。
  • onTertiaryTapDown / onTertiaryTapUp / onTertiaryTapCancel
    类型:类似以上手势的回调函数,但用于第三种点击手势。
  • onDoubleTapDown / onDoubleTap / onDoubleTapCancel
    类型:类似以上手势的回调函数,但用于双击手势。
  • onLongPressDown / onLongPressCancel / onLongPress / onLongPressStart / onLongPressMoveUpdate / onLongPressUp / onLongPressEnd
    类型:类似以上手势的回调函数,但用于长按手势。
  • onSecondaryLongPressDown / onSecondaryLongPressCancel / onSecondaryLongPress / onSecondaryLongPressStart / onSecondaryLongPressMoveUpdate / onSecondaryLongPressUp / onSecondaryLongPressEnd
    类型:类似以上手势的回调函数,但用于次要(右键)长按手势。
  • onTertiaryLongPressDown / onTertiaryLongPressCancel / onTertiaryLongPress / onTertiaryLongPressStart / onTertiaryLongPressMoveUpdate / onTertiaryLongPressUp / onTertiaryLongPressEnd
    类型:类似以上手势的回调函数,但用于第三种长按手势。
  • onVerticalDragDown / onVerticalDragStart / onVerticalDragUpdate / onVerticalDragEnd / onVerticalDragCancel
    类型:类似以上手势的回调函数,但用于垂直拖动手势。
  • onHorizontalDragDown / onHorizontalDragStart / onHorizontalDragUpdate / onHorizontalDragEnd / onHorizontalDragCancel
    类型:类似以上手势的回调函数,但用于水平拖动手势。
  • onForcePressStart / onForcePressPeak / onForcePressUpdate / onForcePressEnd
    类型:类似以上手势的回调函数,但用于压力感应手势。
  • onPanDown / onPanStart / onPanUpdate / onPanEnd / onPanCancel
    类型:类似以上手势的回调函数,但用于平移手势。
  • onScaleStart / onScaleUpdate / onScaleEnd
    类型:类似以上手势的回调函数,但用于缩放手势。
  • behavior
    类型:HitTestBehavior?
    说明:定义命中测试行为。
  • excludeFromSemantics
    类型:bool
    说明:是否从语义树中排除该 widget,默认值为 false。
  • dragStartBehavior
    类型:DragStartBehavior
    说明:定义拖动手势的起始行为,默认值为 DragStartBehavior.start。
  • trackpadScrollCausesScale
    类型:bool
    说明:是否允许触控板滚动引起缩放,默认值为 false。
  • trackpadScrollToScaleFactor
    类型:double
    说明:触控板滚动转换为缩放的比例因子,默认值为 kDefaultTrackpadScrollToScaleFactor。
  • supportedDevices
    类型:Set?
    说明:定义支持哪些设备类型产生的事件。

示例

class GestureDetectorExample extends StatefulWidget {
  @override
  _GestureDetectorExampleState createState() => _GestureDetectorExampleState();
}

class _GestureDetectorExampleState extends State<GestureDetectorExample> {
  String _gesture = 'No Gesture detected';

  void _updateText(String gesture) {
    setState(() {
      _gesture = gesture;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Gesture Detector Example')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            GestureDetector(
              onTap: () => _updateText("Tap"),
              onDoubleTap: () => _updateText("Double Tap"),
              onLongPress: () => _updateText("Long Press"),
              child: Container(
                color: Colors.blue,
                width: 200,
                height: 200,
                child: Center(
                    child:
                        Text(_gesture, style: TextStyle(color: Colors.white))),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

 
 

InkWell

InkWell 是一个 Flutter widget,用于实现点击效果(如波纹效果)。它常用于需要响应用户点击事件的地方,例如按钮。

属性解析

const InkWell({
    super.key,
    super.child,
    super.onTap,
    super.onDoubleTap,
    super.onLongPress,
    super.onTapDown,
    super.onTapUp,
    super.onTapCancel,
    super.onSecondaryTap,
    super.onSecondaryTapUp,
    super.onSecondaryTapDown,
    super.onSecondaryTapCancel,
    super.onHighlightChanged,
    super.onHover,
    super.mouseCursor,
    super.focusColor,
    super.hoverColor,
    super.highlightColor,
    super.overlayColor,
    super.splashColor,
    super.splashFactory,
    super.radius,
    super.borderRadius,
    super.customBorder,
    bool? enableFeedback = true,
    super.excludeFromSemantics,
    super.focusNode,
    super.canRequestFocus,
    super.onFocusChange,
    super.autofocus,
    super.statesController,
    super.hoverDuration,
  })
  • key
    类型:Key?
    说明:控件的键值,用于标识控件。
  • child
    类型:Widget?
    说明:被包裹的子 widget,会响应点击和其他手势。
  • onTap
    类型:GestureTapCallback?
    说明:点击时调用的回调函数。
    签名:void Function()
  • onDoubleTap
    类型:GestureTapCallback?
    说明:双击时调用的回调函数。
    签名:void Function()
  • onLongPress
    类型:GestureLongPressCallback?
    说明:长按时调用的回调函数。
    签名:void Function()
  • onTapDown
    类型:GestureTapDownCallback?
    说明:点击按下时调用的回调函数。
    签名:void Function(TapDownDetails details)
  • onTapUp
    类型:GestureTapUpCallback?
    说明:点击抬起时调用的回调函数。
    签名:void Function(TapUpDetails details)
  • onTapCancel
    类型:GestureTapCancelCallback?
    说明:点击取消时调用的回调函数。
    签名:void Function()
  • onSecondaryTap
    类型:GestureTapCallback?
    说明:次要(右键)点击时调用的回调函数。
    签名:void Function()
  • onSecondaryTapDown
    类型:GestureTapDownCallback?
    说明:次要(右键)点击按下时调用的回调函数。
    签名:void Function(TapDownDetails details)
  • onSecondaryTapUp
    类型:GestureTapUpCallback?
    说明:次要(右键)点击抬起时调用的回调函数。
    签名:void Function(TapUpDetails details)
  • onSecondaryTapCancel
    类型:GestureTapCancelCallback?
    说明:次要(右键)点击取消时调用的回调函数。
    签名:void Function()
  • onHighlightChanged
    类型:ValueChanged?
    说明:高亮状态变化时调用的回调函数。
    签名:void Function(bool value)
  • onHover
    类型:ValueChanged?
    说明:悬停状态变化时调用的回调函数。
    签名:void Function(bool value)
  • mouseCursor
    类型:MouseCursor?
    说明:鼠标指针样式。
  • focusColor
    类型:Color?
    说明:控件获得焦点时的颜色。
  • hoverColor
    类型:Color?
    说明:控件悬停时的颜色。
  • highlightColor
    类型:Color?
    说明:控件高亮时的颜色。
  • overlayColor
    类型:MaterialStateProperty<Color?>?
    说明:材质状态对应的颜色。
  • splashColor
    类型:Color?
    说明:波纹效果的颜色。
  • splashFactory
    类型:InteractiveInkFeatureFactory?
    说明:定义波纹效果的工厂。
  • radius
    类型:double?
    说明:波纹效果的半径。
  • borderRadius
    类型:BorderRadius?
    说明:边框圆角半径。
  • customBorder
    类型:ShapeBorder?
    说明:自定义的边框形状。
    enableFeedback
    类型:bool?
    说明:是否启用点击反馈音效,默认值为 true。
  • excludeFromSemantics
    类型:bool?
    说明:是否从语义树中排除该 widget,默认值为 false。
  • focusNode
    类型:FocusNode?
    说明:用于管理焦点的节点。
  • canRequestFocus
    类型:bool
    说明:是否可以请求焦点,默认值为 true。
  • onFocusChange
    类型:ValueChanged?
    说明:焦点变化时调用的回调函数。
    签名:void Function(bool value)
  • autofocus
    类型:bool
    说明:是否自动获取焦点,默认值为 false。
  • statesController
    类型:MaterialStatesController?
    说明:控制材质状态的控制器。
  • hoverDuration
    类型:Duration?
    说明:悬停状态的持续时间。

示例

class InkWellExample extends StatefulWidget {
  @override
  _InkWellExampleState createState() => _InkWellExampleState();
}

class _InkWellExampleState extends State<InkWellExample> {
  String _gesture = 'No Gesture detected';

  void _updateText(String gesture) {
    setState(() {
      _gesture = gesture;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('InkWell Example')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              InkWell(
                onTap: () => _updateText("Tap"),
                onDoubleTap: () => _updateText("Double Tap"),
                onLongPress: () => _updateText("Long Press"),
                child: Container(
                  color: Colors.blue,
                  width: 200,
                  height: 200,
                  child: Center(
                      child: Text(_gesture,
                          style: TextStyle(color: Colors.white))),
                ),
              ),
            ],
          ),
        ));
  }
}

 
 

Draggable 和 DragTarget

Draggable 是一个 Flutter widget,它使其子 widget 可拖动,并在拖动期间显示反馈。
DragTarget 是一个 Flutter widget,用于接受拖动数据,并在放置拖动对象时触发相应的回调。

Draggable 属性解析

const Draggable({
    super.key,
    required this.child,
    required this.feedback,
    this.data,
    this.axis,
    this.childWhenDragging,
    this.feedbackOffset = Offset.zero,
    this.dragAnchorStrategy = childDragAnchorStrategy,
    this.affinity,
    this.maxSimultaneousDrags,
    this.onDragStarted,
    this.onDragUpdate,
    this.onDraggableCanceled,
    this.onDragEnd,
    this.onDragCompleted,
    this.ignoringFeedbackSemantics = true,
    this.ignoringFeedbackPointer = true,
    this.rootOverlay = false,
    this.hitTestBehavior = HitTestBehavior.deferToChild,
    this.allowedButtonsFilter,
  })
  • key
    类型:Key?
    说明:控件的键值,用于标识控件。
  • child
    类型:Widget
    说明:需要被拖动的子 widget。
  • feedback
    类型:Widget
    说明:当拖动开始时显示的 widget。
  • data
    类型:T?
    说明:要传递给接收器的数据,可以是任何类型。
  • axis
    类型:Axis?
    说明:限制拖动的轴,Axis.horizontal 或 Axis.vertical。
  • childWhenDragging
    类型:Widget?
    说明:拖动过程中替代原子 widget 显示的 widget。
  • feedbackOffset
    类型:Offset
    说明:反馈 widget 相对于指针的位置偏移,默认值为 Offset.zero。
  • dragAnchorStrategy
    类型:DragAnchorStrategy
    说明:确定拖动开始位置的策略,默认值为 childDragAnchorStrategy。
  • affinity
    类型:PointerDeviceKind?
    说明:仅允许指定类型的输入设备(例如触摸或鼠标)进行拖动。
  • maxSimultaneousDrags
    类型:int?
    说明:允许的最大同时拖动次数。
  • onDragStarted
    类型:VoidCallback?
    说明:拖动开始时调用的回调函数。
    签名:void Function()
    onDragUpdate
    类型:DragUpdateCallback?
    说明:拖动过程中调用的回调函数。
    签名:void Function(DragUpdateDetails details)
  • onDraggableCanceled
    类型:DraggableCanceledCallback?
    说明:当拖动被取消时调用的回调函数。
    签名:void Function(Velocity velocity, Offset offset)
  • onDragEnd
    类型:DragEndCallback?
    说明:拖动结束时调用的回调函数。
    签名:void Function(DraggableDetails details)
  • onDragCompleted
    类型:VoidCallback?
    说明:拖动操作完成时调用的回调函数。
    签名:void Function()
  • ignoringFeedbackSemantics
    类型:bool
    说明:是否忽略反馈 widget 的语义树,默认值为 true。
  • ignoringFeedbackPointer
    类型:bool
    说明:反馈 widget 是否忽略指针事件,默认值为 true。
  • rootOverlay
    类型:bool
    说明:是否将反馈 widget 放置到应用程序的根叠加层,默认值为 false。
  • hitTestBehavior
    类型:HitTestBehavior
    说明:命中测试行为,默认值为 HitTestBehavior.deferToChild。
  • allowedButtonsFilter
    类型:AllowedButtonsFilter?
    说明:用于过滤允许的按钮,默认值为 null。

DragTarget属性解析

const DragTarget({
    super.key,
    required this.builder,
    @Deprecated(
      'Use onWillAcceptWithDetails instead. '
      'This callback is similar to onWillAcceptWithDetails but does not provide drag details. '
      'This feature was deprecated after v3.14.0-0.2.pre.'
    )
    this.onWillAccept,
    this.onWillAcceptWithDetails,
    @Deprecated(
      'Use onAcceptWithDetails instead. '
      'This callback is similar to onAcceptWithDetails but does not provide drag details. '
      'This feature was deprecated after v3.14.0-0.2.pre.'
    )
    this.onAccept,
    this.onAcceptWithDetails,
    this.onLeave,
    this.onMove,
    this.hitTestBehavior = HitTestBehavior.translucent,
  })
  • key
    类型:Key?
    说明:控件的键值,用于标识控件。
  • builder
    类型:Widget Function(BuildContext, List<T?>, List)
    说明:用于构建和返回该 widget 子树的函数。通常返回一个包含目标区域的 widget,并根据当前是否有拖动项悬停或已接受来更改其外观。
  • onWillAccept
    类型:DragTargetWillAccept<T?>?
    说明:当拖动项目悬停在此目标上时调用的回调函数,以确定是否接受该项目。(已弃用)
    签名:bool Function(T? data)
  • onWillAcceptWithDetails
    类型:DragTargetWillAcceptWithDetails<T?>?
    说明:当拖动项目悬停在此目标上时调用的回调函数,提供更多的拖动详细信息。
    签名:bool Function(DragTargetDetails<T?> details)
  • onAccept
    类型:DragTargetAccept<T?>?
    说明:当拖动项目被放置在此目标上时调用的回调函数。(已弃用)
    签名:void Function(T? data)
  • onAcceptWithDetails
    类型:DragTargetAcceptWithDetails<T?>?
    说明:当拖动项目被放置在此目标上时调用的回调函数,提供更多的拖动详细信息。
    签名:void Function(DragTargetDetails<T?> details)
  • onLeave
    类型:DragTargetLeave<T?>?
    说明:当拖动项目离开此目标时调用的回调函数。
    签名:void Function(T? data)
  • onMove
    类型:DragTargetMove<T?>?
    说明:当拖动项目移动到此目标区域内时调用的回调函数。
    签名:void Function(DragTargetDetails<T?> details)
  • hitTestBehavior
    类型:HitTestBehavior
    说明:命中测试行为,默认值为 HitTestBehavior.translucent。

示例

class DraggableExample extends StatefulWidget {
  @override
  _DraggableExampleState createState() => _DraggableExampleState();
}

class _DraggableExampleState extends State<DraggableExample> {
  Color _dragColor = Colors.grey;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Draggable and DragTarget Example')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: <Widget>[
              Draggable<Color>(
                data: Colors.blue,
                child: Container(width: 100, height: 100, color: Colors.blue),
                feedback: Container(
                    width: 100,
                    height: 100,
                    color: Colors.blue.withOpacity(0.5)),
                childWhenDragging:
                    Container(width: 100, height: 100, color: Colors.grey),
              ),
              DragTarget<Color>(
                onAccept: (color) {
                  setState(() {
                    _dragColor = color;
                  });
                },
                builder: (context, candidateData, rejectedData) {
                  return Container(
                    width: 200,
                    height: 200,
                    color: _dragColor,
                    alignment: Alignment.center,
                    child: Text('Drop Here',
                        style: TextStyle(color: Colors.white)),
                  );
                },
              ),
            ],
          ),
        ));
  }
}

 
 

Dismissible

Dismissible 是一个 Flutter widget,它允许用户通过滑动手势来移除其子 widget。该 widget 通常用于列表项的实现,例如可以通过滑动来删除某个列表项。

属性解析

  const Dismissible({
    required Key key,
    required this.child,
    this.background,
    this.secondaryBackground,
    this.confirmDismiss,
    this.onResize,
    this.onUpdate,
    this.onDismissed,
    this.direction = DismissDirection.horizontal,
    this.resizeDuration = const Duration(milliseconds: 300),
    this.dismissThresholds = const <DismissDirection, double>{},
    this.movementDuration = const Duration(milliseconds: 200),
    this.crossAxisEndOffset = 0.0,
    this.dragStartBehavior = DragStartBehavior.start,
    this.behavior = HitTestBehavior.opaque,
  })
  • key
    类型:Key
    说明:控件的键值,用于标识和管理控件的状态。必须是唯一的。
  • child
    类型:Widget
    说明:被包裹的子 widget,会响应滑动手势。
  • background
    类型:Widget?
    说明:在滑动时显示的背景 widget,通常用于表示删除或其他操作。
  • secondaryBackground
    类型:Widget?
    说明:当从相反方向滑动时显示的背景 widget。
  • confirmDismiss
    类型:ConfirmDismissCallback?
    说明:滑动到一定位置后调用的回调函数,用于确认是否真的执行消除操作。
    签名:Future<bool?> Function(DismissDirection direction)
  • onResize
    类型:VoidCallback?
    说明:当尺寸变化时调用的回调函数。
  • onUpdate
    类型:DismissingUpdateCallback?
    说明:滑动更新时调用的回调函数。
    签名:void Function(DismissUpdateDetails details)
  • onDismissed
    类型:DismissingCallback?
    说明:滑动完成并确认消除后调用的回调函数。
    签名:void Function(DismissDirection direction)
  • direction
    类型:DismissDirection
    说明:允许滑动的方向,默认值为 DismissDirection.horizontal。
  • resizeDuration
    类型:Duration?
    说明:消除动画的持续时间,默认值为 Duration(milliseconds: 300)。
  • dismissThresholds
    类型:Map<DismissDirection, double>
    说明:滑动达到指定百分比后触发消除操作,默认值为空。
  • movementDuration
    类型:Duration
    说明:滑动动画的持续时间,默认值为 Duration(milliseconds: 200)。
  • crossAxisEndOffset
    类型:double
    说明:滑动结束时的偏移量,默认值为 0.0。
  • dragStartBehavior
    类型:DragStartBehavior
    说明:拖动行为开始时的方式,默认值为 DragStartBehavior.start。
  • behavior
    类型:HitTestBehavior
    说明:命中测试行为,默认值为 HitTestBehavior.opaque。

示例

class DismissibleExample extends StatefulWidget {
  @override
  _DismissibleExampleState createState() => _DismissibleExampleState();
}

class _DismissibleExampleState extends State<DismissibleExample> {
  final List<String> items = List<String>.generate(10, (i) => "Item $i");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Dismissible Example')),
        body: ListView.builder(
          itemCount: items.length,
          itemBuilder: (context, index) {
            final item = items[index];

            return Dismissible(
              key: Key(item),
              onDismissed: (direction) {
                setState(() {
                  items.removeAt(index);
                });

                ScaffoldMessenger.of(context)
                    .showSnackBar(SnackBar(content: Text("$item dismissed")));
              },
              background: Container(color: Colors.red),
              child: ListTile(
                title: Text('$item'),
              ),
            );
          },
        ));
  }
}

 
 

Slider

Slider 是一个 Flutter widget,用于允许用户通过滑动来选择值。

属性解析

const Slider({
    super.key,
    required this.value,
    this.secondaryTrackValue,
    required this.onChanged,
    this.onChangeStart,
    this.onChangeEnd,
    this.min = 0.0,
    this.max = 1.0,
    this.divisions,
    this.label,
    this.activeColor,
    this.inactiveColor,
    this.secondaryActiveColor,
    this.thumbColor,
    this.overlayColor,
    this.mouseCursor,
    this.semanticFormatterCallback,
    this.focusNode,
    this.autofocus = false,
    this.allowedInteraction,
  })
  • key
    类型:Key?
    说明:控件的键值,用于标识控件。
  • value
    类型:double
    说明:当前所选的值,必须在 min 和 max 之间。
  • secondaryTrackValue
    类型:double?
    说明:用于显示在主轨道上方的次要轨道的值。这个值用来创建双滑块效果。
  • onChanged
    类型:ValueChanged?
    说明:当滑块位置发生变化时调用的回调函数。
    签名:void Function(double value)
  • onChangeStart
    类型:ValueChanged?
    说明:滑块开始滑动时调用的回调函数。
    签名:void Function(double startValue)
  • onChangeEnd
    类型:ValueChanged?
    说明:滑块停止滑动时调用的回调函数。
    签名:void Function(double endValue)
  • min
    类型:double
    说明:滑块的最小值,默认值为 0.0。
  • max
    类型:double
    说明:滑块的最大值,默认值为 1.0。
  • divisions
    类型:int?
    说明:将滑块分成几部分,使其只能滑动到这些部分之一。默认值为空,即没有分割。
  • label
    类型:String?
    说明:提供给滑块的标签,通常用于显示滑块的当前值。
  • activeColor
    类型:Color?
    说明:滑块活动部分的颜色。
  • inactiveColor
    类型:Color?
    说明:滑块非活动部分的颜色。
  • secondaryActiveColor
    类型:Color?
    说明:次要滑动轨道的活动颜色。
  • thumbColor
    类型:Color?
    说明:滑块拇指的颜色。
  • overlayColor
    类型:MaterialStateProperty<Color?>?
    说明:滑块拇指的覆盖颜色。
  • mouseCursor
    类型:MouseCursor?
    说明:鼠标悬停在滑块上的光标形状。
  • semanticFormatterCallback
    类型:SemanticFormatterCallback?
    说明:自定义的格式化器,用于生成语义标签。
    签名:String Function(double value)
  • focusNode
    类型:FocusNode?
    说明:用于处理焦点控制。
  • autofocus
    类型:bool
    说明:是否自动获取焦点,默认值为 false。
  • allowedInteraction
    类型:Set?
    说明:允许的交互类型集,例如拖动或点击来调整滑块的值。

示例

class SliderExample extends StatefulWidget {
  @override
  _SliderExampleState createState() => _SliderExampleState();
}

class _SliderExampleState extends State<SliderExample> {
  double _value = 0.0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Slider Example')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Slider(
                value: _value,
                min: 0.0,
                max: 100.0,
                divisions: 100,
                label: _value.round().toString(),
                onChanged: (newValue) {
                  setState(() {
                    _value = newValue;
                  });
                },
              ),
              Text('Value: $_value', style: TextStyle(fontSize: 24)),
            ],
          ),
        ));
  }
}

 
 

Switch

Switch 是一个用于在开和关状态之间切换的 Flutter widget。通常用于设置或选项开关。

属性解析

const Switch({
    super.key,
    required this.value,
    required this.onChanged,
    this.activeColor,
    this.activeTrackColor,
    this.inactiveThumbColor,
    this.inactiveTrackColor,
    this.activeThumbImage,
    this.onActiveThumbImageError,
    this.inactiveThumbImage,
    this.onInactiveThumbImageError,
    this.thumbColor,
    this.trackColor,
    this.trackOutlineColor,
    this.trackOutlineWidth,
    this.thumbIcon,
    this.materialTapTargetSize,
    this.dragStartBehavior = DragStartBehavior.start,
    this.mouseCursor,
    this.focusColor,
    this.hoverColor,
    this.overlayColor,
    this.splashRadius,
    this.focusNode,
    this.onFocusChange,
    this.autofocus = false,
  })
  • key
    类型:Key?
    说明:控件的键值,用于标识控件。
  • value
    类型:bool
    说明:当前开关的状态,true 为开,false 为关。
  • onChanged
    类型:ValueChanged?
    说明:开关状态变化时调用的回调函数。
    签名:void Function(bool value)
    activeColor
    类型:Color?
    说明:开关打开时拇指的颜色。
    activeTrackColor
    类型:Color?
    说明:开关打开时轨道的颜色。
  • inactiveThumbColor
    类型:Color?
    说明:开关关闭时拇指的颜色。
  • inactiveTrackColor
    类型:Color?
    说明:开关关闭时轨道的颜色。
  • activeThumbImage
    类型:ImageProvider?
    说明:开关打开时拇指上显示的图像。
  • onActiveThumbImageError
    类型:ImageErrorListener?
    说明:加载活跃拇指图像失败时的错误处理回调。
  • inactiveThumbImage
    类型:ImageProvider?
    说明:开关关闭时拇指上显示的图像。
  • onInactiveThumbImageError
    类型:ImageErrorListener?
    说明:加载非活跃拇指图像失败时的错误处理回调。
  • thumbColor
    类型:MaterialStateProperty<Color?>?
    说明:拇指的颜色,可以根据不同的 Material state 自定义。
  • trackColor
    类型:MaterialStateProperty<Color?>?
    说明:轨道的颜色,可以根据不同的 Material state 自定义。
  • trackOutlineColor
    类型:MaterialStateProperty<Color?>?
    说明:轨道轮廓线的颜色。
  • trackOutlineWidth
    类型:double?
    说明:轨道轮廓线的宽度。
  • thumbIcon
    类型:MaterialStateProperty<Icon?>?
    说明:拇指上的图标,可以根据不同的 Material state 自定义。
  • materialTapTargetSize
    类型:MaterialTapTargetSize?
    说明:触摸目标的大小配置。
  • dragStartBehavior
    类型:DragStartBehavior
    说明:拖动行为开始时的方式,默认值为 DragStartBehavior.start。
  • mouseCursor
    类型:MouseCursor?
    说明:鼠标悬停在开关上的光标形状。
  • focusColor
    类型:Color?
    说明:开关聚焦时的颜色。
  • hoverColor
    类型:Color?
    说明:鼠标悬停在开关上时的颜色。
  • overlayColor
    类型:MaterialStateProperty<Color?>?
    说明:开关拇指的覆盖颜色。
  • splashRadius
    类型:double?
    说明:水波纹半径。
  • focusNode
    类型:FocusNode?
    说明:用于处理焦点控制。
  • onFocusChange
    类型:ValueChanged?
    说明:焦点状态变化时调用的回调函数。
  • autofocus
    类型:bool
    说明:是否自动获取焦点,默认值为 false。

示例

class SwitchExample extends StatefulWidget {
  @override
  _SwitchExampleState createState() => _SwitchExampleState();
}

class _SwitchExampleState extends State<SwitchExample> {
  bool _isOn = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Switch Example')),
        body: Center(
          child: Switch(
            value: _isOn,
            onChanged: (value) {
              setState(() {
                _isOn = value;
              });
            },
          ),
        ));
  }
}

 
 

Checkbox

Checkbox 是一个用于表示二选一选择的 Flutter widget,通常用于表单或设置列表。

属性解析

const Checkbox({
    super.key,
    required this.value,
    this.tristate = false,
    required this.onChanged,
    this.mouseCursor,
    this.activeColor,
    this.fillColor,
    this.checkColor,
    this.focusColor,
    this.hoverColor,
    this.overlayColor,
    this.splashRadius,
    this.materialTapTargetSize,
    this.visualDensity,
    this.focusNode,
    this.autofocus = false,
    this.shape,
    this.side,
    this.isError = false,
    this.semanticLabel,
  })
  • key
    类型:Key?
    说明:控件的键值,用于标识控件。
  • value
    类型:bool?
    说明:当前复选框的状态,可以是 true(选中)、false(未选中)或 null(不确定状态,仅在 tristate 为 true 时有效)。
  • tristate
    类型:bool
    说明:是否允许三态(true, false, null),默认值为 false。
  • onChanged
    类型:ValueChanged<bool?>?
    说明:复选框状态变化时调用的回调函数。
    签名:void Function(bool? value)
  • mouseCursor
    类型:MouseCursor?
    说明:鼠标悬停在复选框上的光标形状。
  • activeColor
    类型:Color?
    说明:复选框被选中时填充的颜色。
  • fillColor
    类型:MaterialStateProperty<Color?>?
    说明:复选框填充的颜色,可以根据不同的 Material state 自定义。
  • checkColor
    类型:Color?
    说明:复选标记的颜色。
  • focusColor
    类型:Color?
    说明:复选框聚焦时的颜色。
  • hoverColor
    类型:Color?
    说明:鼠标悬停在复选框上时的颜色。
  • overlayColor
    类型:MaterialStateProperty<Color?>?
    说明:复选框的覆盖颜色。
  • splashRadius
    类型:double?
    说明:水波纹半径。
  • materialTapTargetSize
    类型:MaterialTapTargetSize?
    说明:触摸目标的大小配置。
  • visualDensity
    类型:VisualDensity?
    说明:视觉密度,用于调整控件的密集程度。
  • focusNode
    类型:FocusNode?
    说明:用于处理焦点控制。
  • autofocus
    类型:bool
    说明:是否自动获取焦点,默认值为 false。
  • shape
    类型:OutlinedBorder?
    说明:自定义复选框的形状,例如圆角矩形、圆形等。
  • side
    类型:BorderSide?
    说明:复选框边框的样式和颜色。
  • isError
    类型:bool
    说明:是否显示错误状态,这会影响复选框的外观。
  • semanticLabel
    类型:String?
    说明:用于屏幕阅读器的语义标签。

示例

class CheckboxExample extends StatefulWidget {
  @override
  _CheckboxExampleState createState() => _CheckboxExampleState();
}

class _CheckboxExampleState extends State<CheckboxExample> {
  bool _isChecked = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Checkbox Example')),
        body: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Checkbox(
                value: _isChecked,
                onChanged: (bool? value) {
                  setState(() {
                    _isChecked = value ?? false;
                  });
                },
              ),
              Text('Check me!'),
            ],
          ),
        ));
  }
}

 
 

Radio

Radio 是一个用于选择其中一个选项的 Flutter widget,通常用于实现单选按钮组。

属性解析

 const Radio({
    super.key,
    required this.value,
    required this.groupValue,
    required this.onChanged,
    this.mouseCursor,
    this.toggleable = false,
    this.activeColor,
    this.fillColor,
    this.focusColor,
    this.hoverColor,
    this.overlayColor,
    this.splashRadius,
    this.materialTapTargetSize,
    this.visualDensity,
    this.focusNode,
    this.autofocus = false,
  })
  • key
    类型:Key?
    说明:控件的键值,用于标识控件。
  • value
    类型:T
    说明:单选按钮的值,当 groupValue 和 value 相等时,表示该按钮被选中。
  • groupValue
    类型:T?
    说明:当前选中的单选按钮的值。
  • onChanged
    类型:ValueChanged<T?>?
    说明:单选按钮状态变化时调用的回调函数。
    签名:void Function(T? value)
  • mouseCursor
    类型:MouseCursor?
    说明:鼠标悬停在单选按钮上的光标形状。
  • toggleable
    类型:bool
    说明:是否允许取消选择,默认值为 false。
  • activeColor
    类型:Color?
    说明:单选按钮被选中时填充的颜色。
  • fillColor
    类型:MaterialStateProperty<Color?>?
    说明:单选按钮填充的颜色,可以根据不同的 Material state 自定义。
  • focusColor
    类型:Color?
    说明:单选按钮聚焦时的颜色。
  • hoverColor
    类型:Color?
    说明:鼠标悬停在单选按钮上时的颜色。
  • overlayColor
    类型:MaterialStateProperty<Color?>?
    说明:单选按钮的覆盖颜色。
  • splashRadius
    类型:double?
    说明:水波纹半径。
  • materialTapTargetSize
    类型:MaterialTapTargetSize?
    说明:触摸目标的大小配置。
  • visualDensity
    类型:VisualDensity?
    说明:视觉密度,用于调整控件的密集程度。
  • focusNode
    类型:FocusNode?
    说明:用于处理焦点控制。
  • autofocus
    类型:bool
    说明:是否自动获取焦点,默认值为 false。

示例

enum SingingCharacter { lafayette, jefferson }

class RadioExample extends StatefulWidget {
  @override
  _RadioExampleState createState() => _RadioExampleState();
}

class _RadioExampleState extends State<RadioExample> {
  SingingCharacter? _character = SingingCharacter.lafayette;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Checkbox Example')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ListTile(
                title: const Text('Lafayette'),
                leading: Radio<SingingCharacter>(
                  value: SingingCharacter.lafayette,
                  groupValue: _character,
                  onChanged: (SingingCharacter? value) {
                    setState(() {
                      _character = value;
                    });
                  },
                ),
              ),
              ListTile(
                title: const Text('Thomas Jefferson'),
                leading: Radio<SingingCharacter>(
                  value: SingingCharacter.jefferson,
                  groupValue: _character,
                  onChanged: (SingingCharacter? value) {
                    setState(() {
                      _character = value;
                    });
                  },
                ),
              ),
            ],
          ),
        ));
  }
}

 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值