在Flutter中嵌套PageView

时间:2018-07-16 18:58:48

标签: dart flutter

我想将PageViews嵌套起来,在PageView内的Scaffold中使用PageView。在外部PageView中,我将拥有徽标和联系信息以及辅助信息。小时候,我将拥有一个带有内部PageView和BottomNavigationBar作为主要用户交互屏幕的支架。这是我到目前为止的代码:

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget{

    @override
    State<StatefulWidget> createState() {
        return _MyAppState();
  }

}

class _MyAppState extends State<MyApp>{
    int index = 0;
    final PageController pageController = PageController();
    final Curve _curve = Curves.ease;
    final Duration _duration = Duration(milliseconds: 300);

    _navigateToPage(value){
        pageController.animateToPage(
            value,
            duration: _duration,
            curve: _curve
        );
        setState((){
            index = value;
        });
    }

    @override
    Widget build(BuildContext context) {

        return MaterialApp(
            title: 'PageViewCeption',
            home: PageView(
                children: <Widget>[
                    Container(
                        color: Colors.blue,
                    ),
                    Scaffold(
                        body: PageView(
                            controller: pageController,
                            onPageChanged: (page){
                                setState(() {
                                  index = page;
                                });
                            },
                            children: <Widget>[
                                Container(
                                    child: Center(
                                        child: Text('1', style: TextStyle(color: Colors.white))
                                    )
                                ),
                                Container(
                                    child: Center(
                                        child: Text('2', style: TextStyle(color: Colors.white))
                                    )
                                ),
                                Container(
                                    child: Center(
                                        child: Text('3', style: TextStyle(color: Colors.white))
                                    )
                                ),
                            ],
                        ),
                        backgroundColor: Colors.green,
                        bottomNavigationBar: BottomNavigationBar(
                            type: BottomNavigationBarType.fixed,
                            onTap: (value) =>_navigateToPage(value),
                            currentIndex: index,
                            items: [
                                BottomNavigationBarItem(
                                    icon: Icon(Icons.cake),
                                    title: Text('1')
                                ),
                                BottomNavigationBarItem(
                                    icon: Icon(Icons.cake),
                                    title: Text('2')
                                ),
                                BottomNavigationBarItem(
                                    icon: Icon(Icons.cake),
                                    title: Text('3')
                                )
                            ],
                        ),
                    ),
                    Container(
                        color: Colors.blue
                    )
                ],
            ),
        );
    }
}

这是结果:

PageViewCeption

问题是:当我进入内部PageView时,无法离开它到达外部,而在内部PageView的第一页上向左滚动或在最后一页的右页上向右滚动。在BottomNavigationBar上滚动(滑动)返回外层PageView的唯一方法。 在Scroll Physics Class的the docs中,我们在说明中找到了这一点:

  

例如,确定当用户达到最大滚动范围或用户停止滚动时,Scrollable的行为。

但是我还无法提出解决方案。有什么想法吗?

更新1

我在处理CustomScrollPhysics类方面取得了进展:

class CustomScrollPhysics extends ScrollPhysics{

     final PageController _controller;

     const CustomScrollPhysics(this._controller, {ScrollPhysics parent }) : super(parent: parent);

     @override
     CustomScrollPhysics applyTo(ScrollPhysics ancestor) {
       return CustomScrollPhysics(_controller, parent: buildParent(ancestor));
     }

     @override
     double applyBoundaryConditions(ScrollMetrics position, double value) {
       assert(() {
         if (value == position.pixels) {
           throw new FlutterError(
             '$runtimeType.applyBoundaryConditions() was called redundantly.\n'
             'The proposed new position, $value, is exactly equal to the current position of the '
             'given ${position.runtimeType}, ${position.pixels}.\n'
             'The applyBoundaryConditions method should only be called when the value is '
             'going to actually change the pixels, otherwise it is redundant.\n'
             'The physics object in question was:\n'
             '  $this\n'
             'The position object in question was:\n'
             '  $position\n'
           );
         }
         return true;
       }());
       if (value < position.pixels && position.pixels <= position.minScrollExtent){ // underscroll
         _controller.jumpTo(position.viewportDimension + value);
         return 0.0;
       }
       if (position.maxScrollExtent <= position.pixels && position.pixels < value) {// overscroll
         _controller.jumpTo(position.viewportDimension + (value - position.viewportDimension*2));
         return 0.0;
       }
       if (value < position.minScrollExtent && position.minScrollExtent < position.pixels) // hit top edge
         return value - position.minScrollExtent;
       if (position.pixels < position.maxScrollExtent && position.maxScrollExtent < value) // hit bottom edge
         return value - position.maxScrollExtent;
       return 0.0;
     }
}

这是对ClampingScrollPhysics applyBoundaryConditions的修改。有点用,但是由于pageSnapping的原因,它确实有问题。发生这种情况是因为根据the docs

  

任何活动动画都会被取消。如果用户当前正在滚动,则该   操作已取消。

取消操作后,如果用户停止拖动屏幕,则PageView将开始重新捕捉到Scafold页面,这会使事情变得混乱。关于如何避免这种情况下的页面跳动,或者对此有更好的实现的任何想法?

1 个答案:

答案 0 :(得分:1)

我能够在嵌套的PageView上复制问题。内部PageView似乎会覆盖检测到的手势。这解释了为什么我们无法导航到外部PageView的其他页面,而BottomNavigationBar可以导航到其他页面。 thread对此行为进行了详细说明。

作为一种解决方法,您可以使用单个PageView,而只在外部页面上隐藏BottomNavigationBar。我已经修改了您的代码。

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  var index = 0;
  final PageController pageController = PageController();
  final Curve _curve = Curves.ease;
  final Duration _duration = Duration(milliseconds: 300);
  var isBottomBarVisible = false;

  _navigateToPage(value) {
    // When BottomNavigationBar button is clicked, navigate to assigned page
    switch (value) {
      case 0:
        value = 1;
        break;
      case 1:
        value = 2;
        break;
      case 2:
        value = 3;
        break;
    }
    pageController.animateToPage(value, duration: _duration, curve: _curve);
    setState(() {
      index = value;
    });
  }

  // Set BottomNavigationBar indicator only on pages allowed
  _getNavBarIndex(index) {
    if (index <= 1)
      return 0;
    else if (index == 2)
      return 1;
    else if (index >= 3)
      return 2;
    else
      return 0;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'PageViewCeption',
      home: Scaffold(
        body: Container(
          child: PageView(
            controller: pageController,
            onPageChanged: (page) {
              setState(() {
                // BottomNavigationBar only appears on page 1 to 3
                isBottomBarVisible = page > 0 && page < 4;
                print('page: $page bottom bar: $isBottomBarVisible');
                index = page;
              });
            },
            children: <Widget>[
              Container(
                color: Colors.red,
              ),
              Container(
                color: Colors.orange,
              ),
              Container(
                color: Colors.yellow,
              ),
              Container(
                color: Colors.green,
              ),
              Container(color: Colors.lightBlue)
            ],
          ),
        ),
        bottomNavigationBar: isBottomBarVisible // if true, generate BottomNavigationBar
            ? new BottomNavigationBar(
                type: BottomNavigationBarType.fixed,
                onTap: (value) => _navigateToPage(value),
                currentIndex: _getNavBarIndex(index),
                items: [
                  BottomNavigationBarItem(icon: Icon(Icons.cake), label: '1'),
                  BottomNavigationBarItem(icon: Icon(Icons.cake), label: '2'),
                  BottomNavigationBarItem(icon: Icon(Icons.cake), label: '3')
                ],
              )
        //else, create an empty container to hide the BottomNavigationBar
            : Container(
                height: 0,
              ),
      ),
    );
  }
}

enter image description here