在按下时更改容器小部件的背景颜色



我试图改变我的容器小部件的背景颜色在扩展当一个按钮被按在底部导航栏

我使用一个颜色列表和一个变量索引来前后遍历列表。

尽管我使用了setState((){}),但是颜色并没有改变。

h(double x)和w(double x)是使用媒体查询返回屏幕高度或宽度乘以x的方法。

下面是我的代码:

List<Color> col = [Colors.grey, Colors.red, Colors.pink];
int index = 0;

BottomNavigationBar:

bottomNavigationBar: BottomAppBar(
child: Container(
color: Colors.orange,
height: h(0.07),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
icon: Icon(Icons.arrow_back_ios),
color: Colors.white,
onPressed: () {
if (index == 0) {
} else {
setState(() {
index--;
});
}
},
),
Icon(
Icons.color_lens_rounded,
color: Colors.white,
),
IconButton(
icon: Icon(Icons.arrow_forward_ios),
color: Colors.white,
onPressed: () {
if (index == col.length - 1) {
} else {
setState(() {
index++;
});
}
},
),
],
),
),
),

需要更改颜色的小部件

Expanded(
child: Container(
color: col[index],
child: Column(
children: [],
),
),
)

运行此代码,然后希望您可以根据需要修改

import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: Home',
style: optionStyle,
),
Text(
'Index 1: Business',
style: optionStyle,
),
Text(
'Index 2: School',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}

相关内容

  • 没有找到相关文章

最新更新