Flutter 如何在颤振中使用if-else
我是个新手,不知道如何使用if-else语句更改标签的颜色。基本上,这句话给了我错误Flutter 如何在颤振中使用if-else,flutter,dart,label,Flutter,Dart,Label,我是个新手,不知道如何使用if-else语句更改标签的颜色。基本上,这句话给了我错误 selectedItemColor:_selectedIndex == 0 ? Colors.cyan: Colors.grey, **_selectedIndex == 1 ? Colors.cyan: Colors.grey,** 我在底部的导航栏中使用这个,若我使用标题,颤振不接受 @override Widget build(BuildContext context) { retu
selectedItemColor:_selectedIndex == 0 ? Colors.cyan: Colors.grey,
**_selectedIndex == 1 ? Colors.cyan: Colors.grey,**
我在底部的导航栏中使用这个,若我使用标题,颤振不接受
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar( onTap: _onItemTapped, items: [
BottomNavigationBarItem(icon: Icon(Icons.home, color: _selectedIndex == 0 ? Colors.cyan: Colors.grey,), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.ballot, color: _selectedIndex == 1 ? Colors.cyan: Colors.grey,), label: 'Services'),
],
selectedItemColor:_selectedIndex == 0 ? Colors.cyan: Colors.grey,
_selectedIndex == 1 ? Colors.cyan: Colors.grey,
),
appBar: AppBar(
title: Text('Home',
style: TextStyle(
fontFamily: 'Noto Sans TC',
),
),
centerTitle: false,
backgroundColor: HexColor('#09B9B6'),
),
body: PageView(
controller: _pageController,
children: _Screens,
onPageChanged: _onPageChanged,
physics: NeverScrollableScrollPhysics(),
),
);
}
使用
selectedItemColor:\u selectedIndex==0?Colors.cyan:Colors.grey,
告诉Dart将值Colors.cyan
或Colors.grey
分配给命名参数selectedItemColor
。但是,\u选择的索引==1?Colors.cyan:Colors.grey
放错地方了
您可能想要的是这样的:
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar( onTap: _onItemTapped, items: [
BottomNavigationBarItem(icon: Icon(Icons.home, color: _selectedIndex == 0 ? Colors.cyan: Colors.grey,), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.ballot, color: _selectedIndex == 1 ? Colors.cyan: Colors.grey,), label: 'Services'),
],
selectedItemColor:(_selectedIndex == 0||_selectedIndex == 1) ? Colors.cyan: Colors.grey,
),
appBar: AppBar(
title: Text('Home',
style: TextStyle(
fontFamily: 'Noto Sans TC',
),
),
centerTitle: false,
backgroundColor: HexColor('#09B9B6'),
),
body: PageView(
controller: _pageController,
children: _Screens,
onPageChanged: _onPageChanged,
physics: NeverScrollableScrollPhysics(),
),
);
}
当_selectedIndex为0或1时,这将使导航栏呈青色。它被称为三值运算符–
:代码>。根据您当前的逻辑,您应该使用以下代码:
selectedItemColor:_selectedIndex==0 | | _selectedIndex==1?颜色。青色:颜色。灰色
但我看不出有任何理由使用此逻辑来设置BottomNavigationBar
的selectedItemColor
。它将自动设置为所选项目,因此,您可以只使用selectedItemColor:Colors.cyan来代替。但这给了我一个错误,您没有在if-else语句中返回有效的小部件,例如小部件库捕获的此异常======================================================================='package:post/src/rendering/object.dart':失败的断言:第1290行12:'child.parentData!=null”:不正确。导致错误的相关小部件是:BottomNavigationBarfile:///C:/Users/DELL/AndroidStudioProjects/gigoclean/lib/pages/location.dart:52:28I 在当前代码中未发现导致此错误的任何原因。您能在您的答案中添加完整的location.dart
文件和完整的错误日志吗?我解决了那个错误。我没有为BottomNavigationBar创建不同的文件。我不具备BottomNavigationBar的基本知识,仍然面临其他错误