0

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

希望我可以简单地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()),
     )     
  }
}
4

1 回答 1

1

您需要currentIndexcreateViewItem

 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()),
     );
  }
}
于 2020-08-21T19:02:13.880 回答