Dots_Indicator PageView 中的 CurrentIndex 未更新

CurrentIndex is not updated in the Dots_Indicator PageView in flutter

我一直在处理 PageView,我的页面视图工作正常。但是有一个因为我使用 dots_indicator 0.0.4 来表示我现在所在的位置。我对是否该怎么做感到困惑。我的指标显示正常,但问题在于如何更新 index in the position element to update the active dots.

我已经尝试了所有可能的方法来更新它,但它让我感到困惑。我想要的是:

因为我已经尝试过它们,比如创建一个名为 index 的变量,并在我们按下按钮时尝试更新它的值。但它没有更新值。

我不知道我们应该如何在滚动页面时更改值。

当我们点击按钮转到下一页时,我有一个 changePage(),但是 DotsIndicator() 中的索引值没有更新。

代码:

class OnboardingPage extends StatelessWidget {
    final PageController controller = new PageController();
    var index = 0;

    final List<OnboardingPageItem> pages = [
       //I do have a onboarding page widget which is coming up fine
       //so this is not our concern
    ];

    PageView getPages(){
      return PageView(
        controller: this.controller,
        children: this.pages
      );
    }

    //this is a method which controls the button hit for changing the page
    changePage(BuildContext context) {
      //tried here to update the value of the index by assigning the value to it
      //index = this.controller.page.toInt()
      if (this.controller.page >= this.pages.length - 1) {
        Navigator.pushNamed(context, '/signin');
      }
      this.controller.nextPage(duration: Duration(milliseconds: 200), curve: Curves.easeIn);
    }

    @override
    Widget build(BuildContext context) {
      return Material(
       child: Stack(children: <Widget>[
         Positioned(
           left: 24, right: 24, top: 0, bottom: 80, child: this.getPages()),
         Positioned(
           child: DotsIndicator(
             numberOfDot: 3,
             position: this.index,
             dotColor: Theme.of(context).primaryColor.withOpacity(0.5),
             dotActiveSize: new Size(12.0, 12.0),
             dotActiveColor: Theme.of(context).primaryColor
           ),
           bottom: 100.0,
           left: 150.0,
           right: 150.0
         ),
         Positioned(
          child: TMButton(
            text: "Next",
            onPressed: () {changePage(context);},
          ),
          bottom: 24,
          left: 24,
          right: 24
         )
     ]));
   }
}

编辑

我曾尝试使用 this.controller.hasClients 在它变为 true 时进行更新,但对我来说没有任何效果。似乎它是 DotsIndicator 的静态参数。

position: this.controller.hasClients ? this.controller.page.toInt() : this.controller.initialPage;

currentIndex保持在初始页面,完全没有变化。

如有任何帮助,我们将不胜感激。谢谢:)

只要您的小部件中有可修改的 状态 (index),您就不能使用 StatelessWidget,而是创建 StatefulWidget 与相应的 State。并且在修改 index 时将其包装在 setState(() { index = ... ; }); 中,这可确保在状态更改时调用您的 build 方法。

没有隐藏的魔法可以监视您的状态。只有当您调用 StatefulWidgetsetState 时,您的 Widget 才会重建。