未更新 Flutter 选项卡栏屏幕

2izufjch  于 2023-05-08  发布在  Flutter
关注(0)|答案(1)|浏览(124)

我创建了一个更改Tabbar的方法。当我运行这个函数时,有时它的视图会改变,有时不会。但每次索引都在成功更改。并顺利运行全部功能。这是我的函数

class ScreenController extends GetxController with GetTickerProviderStateMixin {
.....

  TabController? profileTabController;
  int profileInitialIndex = 0;
  int profileCurrentIndex = 0;

@override
  onInit() {
    // AppConfig.getVersionStatus();
    profileTabController = TabController(
      vsync: this,
      length: 3,
      initialIndex: profileInitialIndex,
    );
   
    super.onInit();
  }

  //<============================ Change Profile Tabbar
  void changeProfileTabbar(int index) async {
    print("Change Profile Tab 1: $index");

    profileTabController!.index = index >= 0 && index < 3 ? index : 0;
    print("Change Profile Tab 2: ${profileTabController!.index}");
    profileCurrentIndex = index >= 0 && index < 3 ? index : 0;
    print("Change Profile Tab 3: $profileCurrentIndex");
    update();
  }

}

问题出在哪里?为什么有时候屏幕不更新?

06odsfpq

06odsfpq1#

要修复此问题,可以使用TabController的animateTo方法,通过动画更改索引

验证码:

class ScreenController extends GetxController with GetTickerProviderStateMixin {
  TabController? profileTabController;
  int profileInitialIndex = 0;
  int profileCurrentIndex = 0;

  @override
  void onInit() {
    profileTabController = TabController(
      vsync: this,
      length: 3,
      initialIndex: profileInitialIndex,
    );
    super.onInit();
  }

  void changeProfileTabbar(int index) async {
    print("Change Profile Tab 1: $index");

    // animate to the new index instead of setting it directly
    profileTabController!.animateTo(
      index >= 0 && index < 3 ? index : 0,
      duration: Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );

    print("Change Profile Tab 2: ${profileTabController!.index}");
    profileCurrentIndex = index >= 0 && index < 3 ? index : 0;
    print("Change Profile Tab 3: $profileCurrentIndex");
  }
}

相关问题