Flutter:在使用它构建 PageView 之前无法访问 PageController.page

Rak*_*was 6 dart flutter flutter-pageview

如何解决异常 -

未处理的异常:'package:flutter/src/widgets/page_view.dart':失败的断言:第 179 行位置 7:'positions.isNotEmpty':在使用它构建 PageView 之前无法访问 PageController.page。

注意:- 我在两个屏幕中使用它,当我在屏幕之间切换时,它显示上述异常。

@override
  void initState() {
    super.initState();
      WidgetsBinding.instance.addPostFrameCallback((_) => _animateSlider());
  }

  void _animateSlider() {
    Future.delayed(Duration(seconds: 2)).then(
      (_) {
        int nextPage = _controller.page.round() + 1;

        if (nextPage == widget.slide.length) {
          nextPage = 0;
        }

        _controller
            .animateToPage(nextPage,
                duration: Duration(milliseconds: 300), curve: Curves.linear)
            .then(
              (_) => _animateSlider(),
            );
      },
    );
  }
Run Code Online (Sandbox Code Playgroud)

Art*_*ine 13

我没有足够的信息来确切地了解您的问题出在哪里,但我刚刚遇到了一个类似的问题,我想在同一个小部件中对 PageView 和标签进行分组,并且我想将当前幻灯片和标签标记为活动状态,所以我需要访问controler.page才能做到这一点。这是我的修复:

修复了在PageView使用FutureBuilder小部件构建小部件之前访问页面索引的问题

class Carousel extends StatelessWidget {
  final PageController controller;

  Carousel({this.controller});

  /// Used to trigger an event when the widget has been built
  Future<bool> initializeController() {
    Completer<bool> completer = new Completer<bool>();

    /// Callback called after widget has been fully built
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      completer.complete(true);
    });

    return completer.future;
  } // /initializeController()

  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        // **** FIX **** //
        FutureBuilder(
          future: initializeController(),
          builder: (BuildContext context, AsyncSnapshot<void> snap) {
            if (!snap.hasData) {
              // Just return a placeholder widget, here it's nothing but you have to return something to avoid errors
              return SizedBox();
            }

            // Then, if the PageView is built, we return the labels buttons
            return Column(
              children: <Widget>[
                CustomLabelButton(
                  child: Text('Label 1'),
                  isActive: controller.page.round() == 0,
                  onPressed: () {},
                ),
                CustomLabelButton(
                  child: Text('Label 2'),
                  isActive: controller.page.round() == 1,
                  onPressed: () {},
                ),
                CustomLabelButton(
                  child: Text('Label 3'),
                  isActive: controller.page.round() == 2,
                  onPressed: () {},
                ),
              ],
            );
          },
        ),
        // **** /FIX **** //
        PageView(
          physics: BouncingScrollPhysics(),
          controller: controller,
          children: <Widget>[
            CustomPage(),
            CustomPage(),
            CustomPage(),
          ],
        ),
      ],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

修复是否直接在 PageView 子项中需要索引

您可以改用有状态小部件:

class Carousel extends StatefulWidget {
  Carousel();

  @override
  _HomeHorizontalCarouselState createState() => _CarouselState();
}

class _CarouselState extends State<Carousel> {
  final PageController controller = PageController();
  int currentIndex = 0;

  @override
  void initState() {
    super.initState();

    /// Attach a listener which will update the state and refresh the page index
    controller.addListener(() {
      if (controller.page.round() != currentIndex) {
        setState(() {
          currentIndex = controller.page.round();
        });
      }
    });
  }

  @override
  void dispose() {
    controller.dispose();

    super.dispose();
  }

  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
           Column(
              children: <Widget>[
                CustomLabelButton(
                  child: Text('Label 1'),
                  isActive: currentIndex == 0,
                  onPressed: () {},
                ),
                CustomLabelButton(
                  child: Text('Label 2'),
                  isActive: currentIndex == 1,
                  onPressed: () {},
                ),
                CustomLabelButton(
                  child: Text('Label 3'),
                  isActive: currentIndex == 2,
                  onPressed: () {},
                ),
              ]
        ),
        PageView(
          physics: BouncingScrollPhysics(),
          controller: controller,
          children: <Widget>[
            CustomPage(isActive: currentIndex == 0),
            CustomPage(isActive: currentIndex == 1),
            CustomPage(isActive: currentIndex == 2),
          ],
        ),
      ],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

这意味着您正在尝试访问PageController.page(可能是您自己或通过像 Page Indicator 这样的第三方包),但是当时 Flutter 尚未渲染PageView引用控制器的小部件。

最佳解决方案:FutureBuilder使用Future.value

在这里,我们只是使用 的 属性将代码包装pagepageController未来的构建器中,以便在PageView渲染后不久就渲染它。

我们使用Future.value(true)这将导致 Future 立即完成,但仍然等待足够的时间以使下一帧成功完成,因此PageView在我们引用它之前已经构建好了。

class Carousel extends StatelessWidget {

  final PageController controller;

  Carousel({this.controller});

  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[

        FutureBuilder(
          future: Future.value(true),
          builder: (BuildContext context, AsyncSnapshot<void> snap) {
            
            //If we do not have data as we wait for the future to complete,
            //show any widget, eg. empty Container
            if (!snap.hasData) {
             return Container();
            }

            //Otherwise the future completed, so we can now safely use the controller.page
            return Text(controller.controller.page.round().toString);
          },
        ),

        //This PageView will be built immediately before the widget above it, thanks to
        // the FutureBuilder used above, so whenever the widget above is rendered, it will
        //already use a controller with a built `PageView`        

        PageView(
          physics: BouncingScrollPhysics(),
          controller: controller,
          children: <Widget>[
           AnyWidgetOne(),
           AnyWidgetTwo()
          ],
        ),
      ],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

或者

或者,您仍然可以使用在 lifehook中FutureBuilder完成的 future ,因为它也会在渲染当前帧后完成 future,这与上述解决方案具有相同的效果。但我强烈推荐第一个解决方案,因为它很简单addPostFrameCallbackinitState

 WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
     //Future will be completed here 
     // e.g completer.complete(true);
    });

Run Code Online (Sandbox Code Playgroud)


Nuq*_*uqo 6

我认为你可以像这样使用监听器:

int _currentPage;

  @override
  void initState() {
    super.initState();
    _currentPage = 0;
    _controller.addListener(() {
      setState(() {
        _currentPage = _controller.page.toInt();
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)