Flutter/Dart - 获取 PageView.Builder 的索引号以用于文本小部件?

Flutter/Dart - Get index number of PageView.Builder for use in a Text Widget?

我在 StatelessWidget 中有一个 PageView.builder。我需要获取当前查看页面的当前索引号以显示在我构建的文本小部件中。

本来希望我可以简单地使用 currentIndex.toString() 作为文本小部件中的变量,但 Android Studio 将其用红色下划线标出并警告我 undefined name currentIndex。我怎样才能得到正确的变量?

 class StageBuilder extends StatelessWidget {
  final List<SpeakContent> speakcrafts;
  StageBuilder(this.speakcrafts);

  final PageController controller = PageController(initialPage: 0);

  @override
  Widget build(context) {
    return PageView.builder(
      controller: controller,
      itemCount: speakcrafts.length,
      itemBuilder: (context, int currentIndex) {
        return createViewItem(speakcrafts[currentIndex], context);
      },
    );
  }

  Widget createViewItem(SpeakContent speakcraft, BuildContext context) {
  
    return Container(
        child: Text(currentIndex.toString()),
     )     
  }
}

您需要将 currentIndex 传递到您的 createViewItem

 class StageBuilder extends StatelessWidget {
  final List<SpeakContent> speakcrafts;
  StageBuilder(this.speakcrafts);

  final PageController controller = PageController(initialPage: 0);

  @override
  Widget build(context) {
    return PageView.builder(
      controller: controller,
      itemCount: speakcrafts.length,
      itemBuilder: (context, int currentIndex) {
        return createViewItem(speakcrafts[currentIndex], context, currentIndex);
      },
    );
  }

  Widget createViewItem(SpeakContent speakcraft, BuildContext context, int currentIndex) {
  
    return Container(
        child: Text(currentIndex.toString()),
     );
  }
}