flutterradio-buttoniconbutton

Every button changes at once in listview builder but i want to operate specifically or single how can i do that?


Every button changes at once in listview builder but i want to operate specifically or single how can i do that?

This is what happens GIF

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("ListView.builder")),
      body: ListView.builder(
        itemCount: radioDetails.length,
        itemBuilder: (BuildContext context, int index) {
          return Card(
            clipBehavior: Clip.antiAlias,
            child: ListTile(
              title: Text(radioDetails[index].name),
              trailing: IconButton(
                  icon: Icon(
                    (isPlaying) ? Icons.stop : Icons.play_arrow,
                  ),
                  onPressed: () async {
                    setState(() {
                      isPlaying = !isPlaying;
                    });
                    isPlaying == true
                        ? audioPlay(radioDetails[index].url)
                        : audioPause();
                  }),
            ),

Solution

  • It seems that you have the isPlaying state inside the stateful widget which builds the listview. So that one state is applied to all buttons.

    You need to control the state for each list item separately.

    You might include it into your radioDetail object.

    (Guessing what your RadioDetail class might look like...)

    You can add the isPlaying attribute here.

    class RadioDetail {
      final String url;
      final String name;
      bool isPlaying = false;
    
      const RadioDetail(this.url, this.name);
    }
    

    Then in your onPressed write:

    onPressed: () async {
      setState(() {
        radioDetail[index].isPlaying = !radioDetail[index].isPlaying;
      });
    
    

    And the same thing with your icon:

    icon: Icon(
      (radioDetail[index].isPlaying) ? Icons.stop : Icons.play_arrow,
      ),