flutter - 如何在使用 google_nav_bar Flutter 单击选项卡时切换类
问题描述
我正在使用来自 pub 的google_nav_bar和line_icons。
我有 3 个名为 Home()、Likes()、Profile() 的类。我想在单击底部导航栏选项卡时切换类,我已经列出了类,但是我不确定单击选项卡时如何更改类。
这是我到目前为止的代码:
class MainScreen extends StatefulWidget {
@override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
int _page = 0;
final screens = [
Home(),
Likes(),
Profile()
];
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[100],
bottomNavigationBar: GNav(
rippleColor: Colors.grey[300],
hoverColor: Colors.grey[100],
gap: 8,
activeColor: Colors.black,
iconSize: 24,
padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
duration: Duration(milliseconds: 400),
tabBackgroundColor: Colors.grey[100],
color: Colors.black,
tabs: [
GButton(
icon: LineIcons.home,
text: 'Home',
),
GButton(
icon: LineIcons.heart,
text: 'Likes',
),
GButton(
icon: LineIcons.user,
text: 'Profile',
),
],
selectedIndex: _page,
onTabChange: (index) {
setState(() {
_page = index;
});
},
),
body: /*new Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: _page == 0
? Home()
: _page == 1
? Likes()
: Profile(),
),*/
Center(
child: screens.elementAt(_page),
),
);
}
}
我想在单击第二个选项卡时将底部导航栏导航到 Likes() 类,并在单击第三个导航栏时导航到 Profile() 类。
解决方案
一切正常。用不同的小部件替换Tab
小部件,例如Home(), Likes(), Profile().
.
现在它会像
class Tab extends StatelessWidget {
final int tab;
const Tab({
Key? key,
required this.tab,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: Text("$tab"),
);
}
}
class MainScreen extends StatefulWidget {
@override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
int _page = 0;
final screens = const [Tab(tab: 1), Tab(tab: 2), Tab(tab: 3)];
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[100],
bottomNavigationBar: GNav(
rippleColor: Colors.grey[300]!,
hoverColor: Colors.grey[100]!,
gap: 8,
activeColor: Colors.black,
iconSize: 24,
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
duration: const Duration(milliseconds: 400),
tabBackgroundColor: Colors.grey[100]!,
color: Colors.black,
tabs: const [
GButton(
icon: LineIcons.home,
text: 'Home',
),
GButton(
icon: LineIcons.heart,
text: 'Likes',
),
GButton(
icon: LineIcons.user,
text: 'Profile',
),
],
selectedIndex: _page,
onTabChange: (index) {
setState(() {
_page = index;
});
},
),
body: Center(
child: screens[_page],
),
);
}
}
它在你的情况下解决了吗?
推荐阅读
- php - Foreach 循环只处理一个元素
- python - 按月查找每个组中最早的记录
- python - 打开文本文件时出现“OSError:[Errno 36] 文件名太长”
- apache - 带有问号的 URL 重定向
- javascript - 如何用javascript给某个td一个类名?
- javascript - 具有相同状态名称的多个组件,在父div上单击时更改一个而不影响其他人?
- hbase - 带空格的 Hbase 行键
- python - BigTable - 删除/跳过前 N 行
- powershell - 通过 Powershell 获取具有特定域的 Office 365 用户
- unity3d - 跳跃时重力不影响玩家