我正在使用ListView.builder创建音频列表,选择播放项时我需要将其单独更改为播放项,我尝试过bool,但播放或暂停时会更改列表中的所有项,有人可以帮忙吗?
答案 0 :(得分:4)
import 'package:flutter/material.dart';
class Sample extends StatefulWidget {
@override
_SampleState createState() => _SampleState();
}
class _SampleState extends State<Sample> {
bool isPressed = false;
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: [
Column(
children: [
IconButton(
icon: Icon(isPressed
? Icons.play_circle_filled
: Icons.pause_circle_filled),
onPressed: () {
setState(() {
isPressed = !isPressed;
});
}),
IconButton(
icon: Icon(isPressed
? Icons.play_circle_filled
: Icons.pause_circle_filled),
onPressed: () {
setState(() {
isPressed = !isPressed;
});
}),
PlayPause(
isPressed: isPressed,
),
PlayPause(),
],
)
],
),
);
}
}
class PlayPause extends StatefulWidget {
const PlayPause({
Key key,
this.isPressed = false,
}) : super(key: key);
final bool isPressed;
@override
_PlayPauseState createState() => _PlayPauseState();
}
class _PlayPauseState extends State<PlayPause> {
bool _isPressed;
@override
void initState() {
super.initState();
_isPressed = widget.isPressed;
}
@override
Widget build(BuildContext context) {
return IconButton(
icon: Icon(
_isPressed ? Icons.play_circle_filled : Icons.pause_circle_filled),
onPressed: () {
setState(() {
_isPressed = !_isPressed;
});
});
}
}
答案 1 :(得分:2)
您可能具有布尔值列表来保存选择了哪个按钮,然后将布尔值作为参数传递给音频小部件,并使用布尔值来更改图标。
还传递回调函数来更改布尔列表,因为您必须从父窗口小部件中更改列表,因此需要回调函数。
List<bool> audioSelectedList = List.generate(AudioList.length, (i) => false);
// This is a callback function that Audio will call when the button is clicked.
selected(int index){
// set only one bool to be true
setState(() {
audioSelectedList=List.generate(AudioList.length, (i) => false);// set all to false
audioSelectedList[index]=true; // set the selected index to be true
});
}
ListView:
ListView.builder(
itemCount: AudioList.length,
itemBuilder: (context, index) => Audio(
selected: selected, // pass the callback function
index: index, // use to call selected(index)
isSelected: audioSelectedList[index], // only one bool is true in the list which is the selected index.
),
),
答案 2 :(得分:0)
不要为所有音频使用一个布尔值,您可以使用集合为音频列表中的所有内容定义布尔值,然后单击以更改音频的布尔值。