首页 > 解决方案 > 当一个小部件在它前面颤动时在 PageView 中滑动

问题描述

我里面有一个 Stack 和一个 PageView。Stack 中我的 PageView 前面还有一些其他小部件。像这样的东西:

Stack(
  PageView(...),
  Container(...),
  Text(...),
  ....
),

现在,如果我的手指触摸到其他小部件,则我尝试滑动 PageView 滑动采场和操作。

我怎样才能让它工作?

标签: flutterflutter-widgetflutter-pageview

解决方案


小部件树上的 UI 优先级是自下而上,这意味着在渲染Stack小部件时,PageView小部件放置在最后一层,这就是您面临滑动问题的原因。您可能有充分的理由将其他小部件放在PageView. 为了解决这个问题,您可以使用另一个GestureDetector作为子组件的最后一个 WidgetStack并用于PageController在页面之间切换。

Stack(
  PageView(...),
  Container(...),
  Text(...),
///  .... 
    GestureDetector(),///* you can test and set animation, direction, duration etc
),  

完整的小部件

class SwapPV extends StatefulWidget {
  const SwapPV({Key? key}) : super(key: key);

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

class _SwapPVState extends State<SwapPV> {
  PageController controller = PageController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(
      alignment: Alignment.center,
      children: [
        PageView(
          controller: controller,
          children: [
            Container(
              color: Colors.red,
            ),
            Container(
              color: Colors.amber,
            ),
            Container(
              color: Colors.green,
            ),
          ],
        ),
        Container(
          color: Colors.pink.withOpacity(.2),
          child: Text("OverLap Container"),
        ),
        Align(alignment: Alignment(0, .1), child: Text("Another OverLapText")),

        ///THis will controll the PageView
        GestureDetector(
          onTap: () {},
          onPanUpdate: (details) {
            // Swiping in right direction.
            if (details.delta.dx > 0) {
              controller.nextPage(
                  duration: Duration(milliseconds: 200), curve: Curves.easeIn);
            }

            // Swiping in left direction.
            if (details.delta.dx < 0) {
              controller.previousPage(
                  duration: Duration(milliseconds: 200),
                  curve: Curves.easeInOut);
            }
          },
        )
      ],
    ));
  }
}

推荐阅读