我是 Flutter 新手,我想知道是否有任何方法可以将 BottomSheet 添加为 BottomNavigationBarItem?我尝试自己这样做,但它会导致错误。
就像当您按下“添加”按钮时,不会被带到新页面,而是会出现底部工作表来添加项目。
示例 1 - 单击加号图标之前:
示例 2 - 单击加号图标后打开 BottomSheet:
这可能吗,还是我必须为其制作一个自定义导航栏? 这是我的代码:
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int currentIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: pages[currentIndex],
bottomNavigationBar:
BottomNavigationBar(
iconSize: 24,
selectedFontSize: 12,
unselectedItemColor: AppPallete.hintColor,
selectedItemColor: AppPallete.whiteColor,
elevation: 0,
items: [
BottomNavigationBarItem(
icon: Padding(
padding: const EdgeInsets.all(4.0),
child: SvgPicture.asset('assets/svg/folder.svg',
colorFilter: ColorFilter.mode(
currentIndex== 0
?AppPallete.whiteColor
:AppPallete.hintColor, BlendMode.srcIn),
),
),
label: 'Lernsets'
),
BottomNavigationBarItem(
icon: SvgPicture.asset('assets/svg/add.svg',
colorFilter: ColorFilter.mode(
currentIndex== 1
?AppPallete.whiteColor
:AppPallete.hintColor, BlendMode.srcIn),
height: 35,
width: 35,
),
label: '',
),
BottomNavigationBarItem(
icon: Padding(
padding: const EdgeInsets.all(4.0),
child: SvgPicture.asset('assets/svg/profil.svg',
colorFilter: ColorFilter.mode(
currentIndex== 2
?AppPallete.whiteColor
:AppPallete.hintColor, BlendMode.srcIn),
),
),
label: 'Profil',
)
],
type: BottomNavigationBarType.fixed,
currentIndex: currentIndex,
onTap: (index){
setState(() {
currentIndex = index;
});
},
backgroundColor: AppPallete.backgroundColor,
),
);
}
final pages = [
LernsetPage(),
AddSetPage(),
ProfilePage()
];
}
感谢您的帮助。
是的,你可以做到这一点,非常简单。如果您有类型参数,只需像这样更新它即可。
type: BottomNavigationBarType.fixed,
currentIndex: currentIndex,
onTap: (index) {
setState(() {
currentIndex = index;
if (index == 1) {
// Show the bottom sheet when the 'Add' button is pressed
_showAddBottomSheet(context);
}
});
},
您可以将底页设置为:
void _showAddBottomSheet(BuildContext context) {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return Container(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
title: Text('Add Item'),
onTap: () {
print('Item added!');
Navigator.pop(context); // Close the bottom sheet
},
),
],
),
),
);
},
);
}
您可以根据您的需要进行定制。