gpt4 book ai didi

dart - Flutter:使用按钮更改标签栏 View 中的当前标签

转载 作者:IT老高 更新时间:2023-10-28 12:30:03 26 4
gpt4 key购买 nike

我正在创建一个在其主页上包含标签栏的应用。我希望能够导航到标签之一使用我的FloatingActionButton。此外,我想保留导航到该选项卡的默认方法,即通过在屏幕上滑动或单击选项卡。

我还想知道如何将该选项卡链接到其他按钮。

这是我主页的截图。

Homepage with navigation tabs and floating action button

最佳答案

您需要获取 TabBar Controller 并从按钮 onPressed() 句柄调用其 animateTo() 方法。

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),
),
);
}
}

如果您对 MyTabbedPageState 使用 GlobalKey,您可以从任何地方获取 Controller ,因此您可以从以下位置调用 animateTo()任何按钮。

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,
),
);
}
}

你可以在任何地方调用它:

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

关于dart - Flutter:使用按钮更改标签栏 View 中的当前标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50887790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com