Flutter:使用按钮在标签栏视图中更改当前标签 [英] Flutter: Changing the current tab in tab bar view using a button
问题描述
我正在创建一个应用,该应用的首页上包含一个标签栏。我希望能够使用我的 FloatingActionButton
导航到一个选项卡。另外,我想保留导航到该选项卡的默认方法,即通过在屏幕上滑动或单击该选项卡。
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 FloatingActionButton
. In addition, I want to keep the default methods of navigating to that tab, i.e. by swiping on screen or by clicking the tab.
我还想知道如何链接该标签到其他按钮。
I also want to know how to link that tab to some other button.
这是我主页的屏幕截图。
Here is a screenshot of my homepage.
推荐答案
您需要获取 TabBar
控制器,并从按钮<$ c中调用其 animateTo()
方法$ c> onPressed()句柄。
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<MyTabbedPage> with SingleTickerProviderStateMixin {
final List<Tab> myTabs = <Tab>[
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),
),
);
}
}
如果使用 GlobalKey
用于 MyTabbedPageState
,您可以从任何位置获取控制器,因此可以调用 animateTo()$ c
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(...);
这篇关于Flutter:使用按钮在标签栏视图中更改当前标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!