在我的Flutter应用程序中,我想定义自定义AppBar
个动作.必须在子小部件中定义该操作单击时调用的方法(在我的情况下是Page1
或Page2
),因为在这些小部件中有Bloc
个提供者等,因此不可能在Home
小部件中直接定义方法.
我将Home
个小部件定义如下:
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
int _selectedIndex = 0;
static final List<Widget> _options = <Widget>[
const Center(child: Page1()),
const Center(child: Page2()),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(""),
actions: [
],
),
body: IndexedStack(index: _selectedIndex, children: _options),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(label: "P1", icon: Icon(Icons.home)),
BottomNavigationBarItem(label: "P2", icon: Icon(Icons.home)),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.blue,
onTap: _onItemTapped,
),
);
}
}
有什么方法可以做到这一点吗?我try 用Provider
来执行,但这种方式不适合,因为有IndexedStack
(因此当我在构建方法中调用AppBar更改时,它只被调用一次,而不是每次我进入该特定页面时).