Кнопка "Назад" ведет на самую первую страницу - PullRequest
0 голосов
/ 05 мая 2020

Я использую панель вкладок DefaultTabController, которая выглядит так

class MainTabs extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        appBar: MyAppbar(),
        body: TabBarView(
          children: [
            CardContentPage(title: 'Tab1'),
            DeviceContentPage(title: 'Tab2'),
            SettingsPage(title: 'Tab2'),
          ],
        ),
      ),
    );
  }
}

Но при таком дизайне кнопка возврата всегда ведет к самой первой странице приложения.

Как я могу настроить так, чтобы кнопка возврата работала должным образом с DefaultTabController?

1 Ответ

2 голосов
/ 06 мая 2020

Используя DefaultTabController, вы можете просто предотвратить возврат пользователя с помощью WillPopScope:

DefaultTabController(
  initialIndex: 0,
  length: 3,
  child: WillPopScope(
    onWillPop: () async {
      return false;
    },
    child: Scaffold(
      appBar: AppBar(
        bottom: TabBar(tabs: [
          Tab(text: 'First',),
          Tab(text: 'Second',),
          Tab(text: 'Third',),
        ]),
      ),
      body: TabBarView(
        children: [
          Container(color: Colors.red,),
          Container(color: Colors.yellow,),
          Container(color: Colors.green,),
        ],
      ),
    ),
  ),
);

Но с TabController вы можете установить маршрут к предыдущей странице:

class TabPage extends StatefulWidget {
  @override
  _TabPageState createState() => _TabPageState();
}

class _TabPageState extends State<TabPage> with SingleTickerProviderStateMixin {
  TabController tabController;

  @override
  void initState() {
    tabController = TabController(length: 3, vsync: this);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        bottom: TabBar(
          controller: tabController,
          tabs: [
            Tab(
              text: 'First',
            ),
            Tab(
              text: 'Second',
            ),
            Tab(
              text: 'Third',
            ),
          ],
        ),
      ),
      body: TabBarView(
        controller: tabController,
        children: [
          Container(
            color: Colors.red,
          ),
          WillPopScope(
            onWillPop: () async {
              tabController.animateTo(0, duration: Duration(milliseconds: 500),);
              return false;
            },
            child: Container(
              color: Colors.yellow,
            ),
          ),
          WillPopScope(
            onWillPop: ()async {
              tabController.animateTo(1, duration: Duration(milliseconds: 500),);
              return false;
            },
            child: Container(
              color: Colors.green,
            ),
          ),
        ],
      ),
    );
  }
}
...