Flutter: Changing the current tab in tab bar view using a button

后端 未结 5 1844
北荒
北荒 2020-12-12 15:24

I am creating an app that contains a tab bar on its homepage. I want to be able to navigate to one of the tabs using my FloatingActio

5条回答
  •  既然无缘
    2020-12-12 15:59

    You need to get the TabBar controller and call its animateTo() method from the button onPressed() handle.

    import 'package:flutter/material.dart';
    
    void main() => runApp(new MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: 'Flutter Demo',
          home: new MyTabbedPage(),
        );
      }
    }
    
    class MyTabbedPage extends StatefulWidget {
      const MyTabbedPage({Key key}) : super(key: key);
    
      @override
      _MyTabbedPageState createState() => new _MyTabbedPageState();
    }
    
    class _MyTabbedPageState extends State with SingleTickerProviderStateMixin {
      final List myTabs = [
        new Tab(text: 'LEFT'),
        new Tab(text: 'RIGHT'),
      ];
    
      TabController _tabController;
    
      @override
      void initState() {
        super.initState();
        _tabController = new TabController(vsync: this, length: myTabs.length);
      }
    
      @override
      void dispose() {
        _tabController.dispose();
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text("Tab demo"),
            bottom: new TabBar(
              controller: _tabController,
              tabs: myTabs,
            ),
          ),
          body: new TabBarView(
            controller: _tabController,
            children: myTabs.map((Tab tab) {
              return new Center(child: new Text(tab.text));
            }).toList(),
          ),
          floatingActionButton: new FloatingActionButton(
            onPressed: () => _tabController.animateTo((_tabController.index + 1) % 2), // Switch tabs
            child: new Icon(Icons.swap_horiz),
          ),
        );
      }
    }
    

    If you use a GlobalKey for the MyTabbedPageState you can get the controller from any place, so you can call the animateTo() from any button.

    class MyApp extends StatelessWidget {
      static final _myTabbedPageKey = new GlobalKey<_MyTabbedPageState>();
    
      @override
      Widget build(BuildContext context) {
        return new MaterialApp(
          title: 'Flutter Demo',
          home: new MyTabbedPage(
            key: _myTabbedPageKey,
          ),
        );
      }
    }
    

    You could call it from anywhere doing:

    MyApp._myTabbedPageKey.currentState._tabController.animateTo(...);

提交回复
热议问题