【发布时间】:2021-07-20 01:15:54
【问题描述】:
我是 Flutter 的新手,我试图在按钮处于活动状态(被按下)时更改按钮的颜色,但我的代码没有按预期工作。有人知道我该如何解决吗?
我的代码:
import 'package:flutter/material.dart';
class BottomNavBar extends StatefulWidget {
const BottomNavBar({Key? key}) : super(key: key);
@override
_BottomNavBarState createState() => _BottomNavBarState();
}
class _BottomNavBarState extends State<BottomNavBar> {
int _selectedIndex = 0;
@override
Widget build(BuildContext context) {
return Container(
child: Row(
children: <Widget>[
iconButtonBar(context, Icons.home, 0, _selectedIndex),
iconButtonBar(context, Icons.favorite, 1, _selectedIndex),
iconButtonBar(context, Icons.person, 2, _selectedIndex),
iconButtonBar(context, Icons.search, 3, _selectedIndex),
],
),
);
}
Container iconButtonBar(
BuildContext context, IconData icon, int index, int _selectedIndex) {
return Container(
height: 60,
width: MediaQuery.of(context).size.width / 4,
color: index == _selectedIndex ? Colors.blue : Colors.white, // changing the color
child: IconButton(
icon: Icon(icon),
onPressed: () {
_selectedIndex = index;
},
));
}
}
如果你有时间回答,真的很高兴。
【问题讨论】: