You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中实现可在屏幕侧边(左右/上下)移动的Widget

实现侧边可上下拖动的悬浮按钮

先修正你代码里的构造函数错误,再添加拖动逻辑,让按钮固定在屏幕侧边(左/右)并支持上下拖动:

import 'package:flutter/material.dart';

import '../../../core/utils/styles/button.dart';

class BtnShowTypesOfApartments extends StatefulWidget {
  // 修正构造函数参数写法错误
  const BtnShowTypesOfApartments({super.key, required this.onPressed});
  final void Function()? onPressed;

  @override
  State<BtnShowTypesOfApartments> createState() => _BtnShowTypesOfApartmentsState();
}

class _BtnShowTypesOfApartmentsState extends State<BtnShowTypesOfApartments> {
  late Offset _position;
  final double _buttonWidth = 100;
  final double _buttonHeight = 35;
  // 侧边边距,可自定义
  final double _sideMargin = 8;

  @override
  void initState() {
    super.initState();
    final screenSize = MediaQuery.of(context).size;
    // 初始位置:右侧屏幕中间
    _position = Offset(
      screenSize.width - _buttonWidth - _sideMargin,
      (screenSize.height - _buttonHeight) / 2,
    );
  }

  // 处理拖动更新,仅允许上下移动
  void _onPanUpdate(DragUpdateDetails details) {
    final screenSize = MediaQuery.of(context).size;
    setState(() {
      // 计算新的y坐标,限制在屏幕范围内,避免超出上下边界
      double newY = _position.dy + details.delta.dy;
      newY = newY.clamp(
        0,
        screenSize.height - _buttonHeight,
      );
      // 保持x坐标固定在右侧(要改左侧的话,把dx改成_sideMargin即可)
      _position = Offset(screenSize.width - _buttonWidth - _sideMargin, newY);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned(
          // 固定在右侧,切换左侧只需换成left: _sideMargin,注释掉right
          right: _sideMargin,
          top: _position.dy,
          child: GestureDetector(
            // 添加拖动监听
            onPanUpdate: _onPanUpdate,
            child: OutlinedButton(
              style: outlineButton,
              onPressed: widget.onPressed,
              child: Container(
                padding: const EdgeInsets.only(top: 4),
                height: _buttonHeight,
                width: _buttonWidth,
                color: Colors.white,
                child: const Text(" صنف السكن ", textAlign: TextAlign.center),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

关键说明:

  • 用Stack + Positioned实现按钮悬浮定位,不会干扰其他组件布局
  • 通过GestureDetector监听拖动事件,仅更新y轴坐标,确保按钮始终贴在侧边,只能上下移动
  • 用clamp方法限制y轴范围,避免按钮被拖出屏幕外
  • 如需切换到左侧,只需修改Positioned的定位参数,同步调整初始化和拖动逻辑里的x坐标即可

内容的提问来源于stack exchange,提问作者user18104691

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 06:16:03