[英]Flutter switch between pages loaded using BottomNavigationBar
I have created Flutter home page with BottomNavigationBar by following this link https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html我通过以下链接创建了带有 BottomNavigationBar 的 Flutter 主页https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html
It is working fine.它工作正常。 But I wanted to know how to go to the first page from the third page.
但是我想知道如何从第三页转到第一页。 I mean, inside the third page, I have a button, when the user clicks on it, I have to redirect the user to the first page.
我的意思是,在第三页内,我有一个按钮,当用户点击它时,我必须将用户重定向到第一页。 ( I'm not speaking about the button on the bottom navigation bar )
(我不是在说底部导航栏上的按钮)
Is it possible?是否可以?
Just change the _selectedIndex
and call the setState
method,like this:只需更改
_selectedIndex
并调用setState
方法,如下所示:
class TestWidget extends StatefulWidget {
@override
_TestWidgetState createState() => _TestWidgetState();
}
class _TestWidgetState extends State<TestWidget>
with SingleTickerProviderStateMixin {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
List<Widget> _widgetOptions;
@override
void initState() {
super.initState();
_widgetOptions = <Widget>[
Text(
'Index 0: Home',
style: optionStyle,
),
Text(
'Index 1: Business',
style: optionStyle,
),
TestBusinessPage<Object>((data,index){
_onItemTapped(index);
}),
];
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
title: Text('Business'),
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
title: Text('School'),
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}
/// T is business data,index is target index
typedef void OnButtonClicked<T>(T data, int index);
class TestBusinessPage<T> extends StatelessWidget {
final OnButtonClicked buttonClicked;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
TestBusinessPage(this.buttonClicked);
@override
Widget build(BuildContext context) {
return Container(
child: RaisedButton(
onPressed: () {
buttonClicked(null,0);
},
child: Text(
'Index 2: School',
style: optionStyle,
),
),
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.