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

标签 flutter dart 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(),
            );
      },
    );
  }

最佳答案

我没有足够的信息来准确了解您的问题出在哪里,但我刚刚遇到了一个类似的问题,我想在同一个小部件中对 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(),
          ],
        ),
      ],
    );
  }
}

修复是否直接在 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),
          ],
        ),
      ],
    );
  }
}

关于Flutter : PageController. 页面在使用它构建 PageView 之前无法访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61058420/

相关文章:

flutter - 如何构建具有空安全性的空工厂构造函数?

android-studio - 是否可以给索引指定一个日期,然后使用jumpToPage设置该日期?

flutter - flutter中同步PageView和Slider的换页

flutter - 等待多个级别的 future ?

flutter - 在 flutter 应用程序的每个 View 的底部显示音乐播放器

dart - 如何计算不稳定性和抽象度

arrays - 需要将 JSON 数据提取字段配置到 flutter 中的小部件元素

firebase - E/StorageUtil(6584) : error getting token java. util.concurrent.ExecutionException : b. a.d.p.d.a:请先登录,然后再尝试获取 token

dart - 是否可以使用 Flutter 提供的 Dart SDK 作为 AngularDart 的 SDK?

http - 使用 JSON 数组的 Flutter POST