#flutter #dart
Вопрос:
У меня есть следующий код
TextButton(
onPressed: () {
setState(() {
for (int i = 0; i == seasonList.length; i ) {
seasonList[i].color = 0xff808080; //grey
}
seasonList[index].color = 0xff000000; //black
});
},
В значительной степени этот код должен делать то, что, когда я нажимаю на TextButton
все остальные кнопки, они снова должны становиться серыми, а только нажатая черная. Однако в конечном итоге происходит то, что мой код действует так, как будто цикла for вообще не существовало, делая каждую кнопку черной, когда я нажимаю на нее, но оставляя их черными, когда я нажимаю другую.
Пожалуйста, дайте мне знать, в чем дело.
Полный код:
import 'package:flutter/material.dart';
void main() => runApp(TradingPage());
Season venus = Season('Venus');
Season helado = Season('Helado');
Season year1800s = Season('1800s');
Season neonArt = Season('Neon Art');
Season ritmo = Season('Ritmo');
Season lente = Season('Lente');
Season joyasPreciosas = Season('Joyas');
List<Season> seasonList = [
venus,
helado,
year1800s,
neonArt,
ritmo,
lente,
joyasPreciosas,
];
class TradingPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.pink,
title: Text(
'Relatable',
style: TextStyle(color: Colors.white),
),
),
body: Column(
children: [
Container(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 3,
blurRadius: 6,
offset: Offset(0, 1),
)
],
),
width: double.infinity,
height: 30.0,
child: chooseSeasonBar(),
),
],
),
),
);
}
}
class chooseSeasonBar extends StatefulWidget {
@override
_chooseSeasonBarState createState() => _chooseSeasonBarState();
}
class _chooseSeasonBarState extends State<chooseSeasonBar> {
@override
Widget build(BuildContext context) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return TextButton(
onPressed: () {
for (int i = 0; i == seasonList.length; i ) {
setState(() {
seasonList[i].color = 0xff808080; //grey
});
}
setState(() {
seasonList[index].color = 0xff000000; //black
});
},
child: Container(
width: 100.0,
child: Text(
seasonList[index].name,
style: TextStyle(color: Color(seasonList[index].color)), //grey
textAlign: TextAlign.center,
),
),
);
},
itemCount: seasonList.length,
);
}
}
class Season {
String name;
int color = 0xff808080; //grey
Season(this.name);
}
Комментарии:
1. Вы можете попытаться поместить состояние набора в поле для?
2. @Y. Сампайо не работал 🙁
3. Ваше состояние цикла находится в обратном порядке, поэтому ваш цикл никогда не будет повторяться.
Ответ №1:
попробуй вот так
seasonList.forEach((element) {
setState(() {
element.color = 0xff808080;
});
});
setState(() {
seasonList[index].color = 0xff000000;
});
Комментарии:
1. Работает! Спасибо!!
2. Смотрите мой комментарий к вопросу о том, почему исходный код не сработал. Кроме того, вы обычно должны предпочитать
for-in
циклы использованиюforEach
.
Ответ №2:
Это должно работать с одним вызовом setState…
для (int i = 0; i < Список сезонов.длина; i )
onPressed: () {
for (int i = 0; i < seasonList.length; i ) {
seasonList[i].color = 0xff808080;
}
seasonList[index].color = 0xffff0000;
setState(() => {});
}