flutter FloatingActionButton 在指定TabBarView页面显示
时间: 2024-05-12 16:13:09 浏览: 110
FloatingActionbutton
要在指定的TabBarView页面中显示FloatingActionButton,可以将FloatingActionButton放置在Scaffold组件的bottomNavigationBar属性中,在TabBarView组件的子页面中,可以通过Scaffold.of(context)来获取父级Scaffold组件,然后使用ScaffoldState.showSnackBar或者ScaffoldState.showBottomSheet方法来显示SnackBar或BottomSheet。
以下是示例代码:
```dart
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
final List<Tab> tabs = [
Tab(text: "Tab 1"),
Tab(text: "Tab 2"),
Tab(text: "Tab 3"),
];
TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(length: tabs.length, vsync: this);
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("My App"),
bottom: TabBar(
controller: _tabController,
tabs: tabs,
),
),
bottomNavigationBar: FloatingActionButton(
onPressed: () {
Scaffold.of(context).showSnackBar(SnackBar(
content: Text("Button Pressed"),
));
},
child: Icon(Icons.add),
),
body: TabBarView(
controller: _tabController,
children: <Widget>[
Center(child: Text("Tab 1")),
Center(child: Text("Tab 2")),
Center(child: Text("Tab 3")),
],
),
);
}
}
```
在此示例中,我们将FloatingActionButton放置在Scaffold的bottomNavigationBar属性中,并在其onPressed回调中显示一个SnackBar。在TabBarView的子页面中,我们可以使用Scaffold.of(context)来获取父级Scaffold组件,并在需要时显示SnackBar或BottomSheet。
阅读全文