我正在使用AppBar
和BottomNavigationBar
开发 Flutter 应用程序。这是代码:
class MainPage extends StatefulWidget {
final MainModel model;
MainPage(this.model);
@override
State<StatefulWidget> createState() {
return _MainPageState();
}
}
class _MainPageState extends State<MainPage> {
int _selectedIndex = 0;
Widget _openSelectedPage() {
switch(_selectedIndex) {
case 0:
return HomePage(widget.model);
case 1:
return CapturePage(widget.model);
case 2:
return MealsPage(widget.model);
default:
return HomePage(widget.model);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My App'),
),
body: _openSelectedPage(),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.camera_alt),
title: Text('Capture'),
),
BottomNavigationBarItem(
icon: Icon(Icons.format_list_bulleted),
title: Text('Meals'),
),
],
currentIndex: _selectedIndex,
onTap: (int index) {
setState(() {
_selectedIndex = index;
});
}
),
);
}
}
如何在AppBar
上自定义MealsPage
?如果我在Scaffold
的{{1}}方法中添加另一个build
,则它将创建两个MealsPage
,这不是我想要的。我只想拥有一个AppBar
,即我在AppBar
中定义的那个。
答案 0 :(得分:1)
class MainPage extends StatefulWidget {
final MainModel model;
MainPage(this.model);
@override
State<StatefulWidget> createState() {
return _MainPageState();
}
}
class _MainPageState extends State<MainPage> {
int _selectedIndex = 0;
Widget _openSelectedPage() {
switch (_selectedIndex) {
case 0:
return HomePage(widget.model);
case 1:
return CapturePage(widget.model);
case 2:
return MealsPage(widget.model);
default:
return HomePage(widget.model);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: _selectedIndex == 2 ? null : AppBar(title: Text('My App')),
body: _openSelectedPage(),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.camera_alt),
title: Text('Capture'),
),
BottomNavigationBarItem(
icon: Icon(Icons.format_list_bulleted),
title: Text('Meals'),
),
],
currentIndex: _selectedIndex,
onTap: (int index) {
setState(() {
_selectedIndex = index;
});
},
),
);
}
}