假設我有一個提升按鈕的串列。
List<ElevatedButton> buttonsList = [];
現在我想對該串列使用 onpress 功能。就像如果我按下buttonList[i]然后只有 onpress 功能將buttonList[i]不適用于整個串列。例如我想改變第三個按鈕的顏色然后只有第三個按鈕會改變顏色,而不是串列中的所有按鈕。知道我該怎么做嗎?
uj5u.com熱心網友回復:
正如@Chance 所說,最好使用 value,但出于好奇的目的,請測驗此小部件。
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
List<ElevatedButton> buttonsList = [];
int _currentItem = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
//list of buttons
...buttonsList.map((e) => e),
//To create one
ElevatedButton(
onPressed: () {
setState(
() {
final value = _currentItem.toInt(); // creating new value , dont use `_currentItem` direclty, check pass by value vs reference
buttonsList.add(
ElevatedButton(
onPressed: () {
print("Tapped item $value");
},
child: Text("item $value"),
),
);
_currentItem ;
},
);
},
child: Text("add ${_currentItem 1}"),
)
],
));
}
}
uj5u.com熱心網友回復:
好吧,我會以這種方式處理屬性串列。看看對你有沒有幫助。每當您在串列中插入新屬性時,該元素將出現在未選中的串列視圖中。
class ButtonProperties {
String label;
Color color;
bool selected;
ButtonProperties(
{required this.label, this.color = Colors.black, this.selected = false});
}
class MyButtonList extends StatefulWidget {
const MyButtonList({Key? key}) : super(key: key);
@override
_MyButtonListState createState() => _MyButtonListState();
}
class _MyButtonListState extends State<MyButtonList> {
List<ButtonProperties> buttonsList = [
ButtonProperties(label: 'Button 1'),
ButtonProperties(label: 'Button 2'),
ButtonProperties(label: 'Button 3'),
ButtonProperties(label: 'Button 4'),
ButtonProperties(label: 'Button 5'),
ButtonProperties(label: 'Button 6'),
ButtonProperties(label: 'Button 7'),
ButtonProperties(label: 'Button 8'),
ButtonProperties(label: 'Button 9'),
];
void _onChangeButtonColor(int index) {
setState(() {
if (buttonsList[index].selected) {
buttonsList[index].selected = false;
buttonsList[index].color = Colors.black;
} else {
buttonsList[index].selected = true;
buttonsList[index].color = Colors.red;
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Button List')),
body: ListView.builder(
padding: const EdgeInsets.all(15),
itemCount: buttonsList.length,
itemBuilder: (context, index) {
return ElevatedButton(
onPressed: () => _onChangeButtonColor(index),
child: Text(
'${buttonsList[index].label}',
style: TextStyle(color: buttonsList[index].color),
));
}),
);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/369384.html
