我试图实现在一个扑动应用程序的底部导航栏,但我不断得到错误在我的源代码



class BottomNavigationBar extends StatefulWidget {
const BottomNavigationBar({super.key});
@override
State<BottomNavigationBar> createState() => _BottomNavigationBarState();
}
class _BottomNavigationBarState extends State<BottomNavigationBar> {
List views = [
const HomeView(),
const CurrentLocationView(),
const ProfileView(),
const SettingsView()
];
int currentIndex = 0;
void onTap(int index) {
currentIndex = index;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: views[0],
bottomNavigationBar:const BottomNavigationBar(
onTap: onTap,
currentIndex:currentIndex,
selectedItemColor: Colors.black54,
unselectedItemColor: Colors.grey.withOpacity(0.5),
showUnselectedLabels: false,
showSelectedLabels: false,
elevation:0,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'Home',
icon: Icon(Icons.home_outlined),
),
BottomNavigationBarItem(
label: 'Map',
icon: Icon(Icons.map),
),
BottomNavigationBarItem(
label: 'Settings',
icon: Icon(Icons.settings),
),
BottomNavigationBarItem(
label: 'Profile',
icon: Icon(Icons.person),
),
],
),
);
}
}

在Visual studio代码中,它突出显示以下代码片段,我将在下面以红色发布,并给出以下错误信息:

名称"onTap"没有定义。尝试将名称更正为现有的命名参数名称,或者使用名称onTap

定义命名参数。名称"currentIndex"没有定义。尝试将名称更正为现有的命名参数名称,或使用名称"currentIndex."定义命名参数

名称"item "没有定义。尝试将名称更正为现有的命名参数名称,或者使用名称"items.">

"定义命名参数。对于下面的其他六行代码,它给出相同的错误。

onTap: onTap,
currentIndex:currentIndex,
selectedItemColor: Colors.black54,
unselectedItemColor: Colors.grey.withOpacity(0.5),
showUnselectedLabels: false,
showSelectedLabels: false,
elevation:0,
items: <BottomNavigationBarItem>[

onTap是一个函数,当用户更改选项卡时返回所选选项卡索引。它给出了红色错误,因为你没有定义onTap函数。

使用代码如下,

onTap: (int index) {
print("selected Tab Index : $index");
}

这是因为您定义的类(BottomNavigationBar)与Flutter自带的预构建类相同。你需要改变

import 'package:flutter/material.dart';
class BottomNavigationScreen extends StatefulWidget { ////here, class name should be different from flutter built in classes
const BottomNavigationScreen({super.key});
@override
State<BottomNavigationScreen> createState() => _BottomNavigationScreenState();
}
class _BottomNavigationScreenState extends State<BottomNavigationScreen> {
List views = [
const HomeView(),
const CurrentLocationView(),
const ProfileView(),
const SettingsView()
];
int currentIndex = 0;
void onTap(int index) {
currentIndex = index;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: views[0],
bottomNavigationBar:BottomNavigationBar(
onTap: onTap,
currentIndex:currentIndex,
selectedItemColor: Colors.black54,
unselectedItemColor: Colors.grey.withOpacity(0.5),
showUnselectedLabels: false,
showSelectedLabels: false,
elevation:0,
items: const<BottomNavigationBarItem>[
BottomNavigationBarItem(
label: 'Home',
icon: Icon(Icons.home_outlined),
),
BottomNavigationBarItem(
label: 'Map',
icon: Icon(Icons.map),
),
BottomNavigationBarItem(
label: 'Settings',
icon: Icon(Icons.settings),
),
BottomNavigationBarItem(
label: 'Profile',
icon: Icon(Icons.person),
),
],
),
);
}
}

最新更新