【问题标题】:Flutter ListView changing valuesFlutter ListView 改变值
【发布时间】:2021-08-23 05:37:42
【问题描述】:

我有一个问题: 我在 Flutter with Songs 中有一个 ListView.builder,每个 Song 项目的左侧都有一个播放按钮。所以我点击播放按钮,图标发生变化,歌曲开始播放。 当我单击列表中的另一首歌曲时,如何将图标设置为停止上一首歌曲?就像在这个视频中一样:

https://youtu.be/zAXN1QQMM-4

所以只需将前一个图标的图标/布尔值设置为 false,将新图标设置为 true。

【问题讨论】:

  • 请提供您的代码,您目前取得的成果
  • 对不起,我没有任何有价值的东西,只有带有布尔值的列表视图构建器

标签: list flutter listview boolean audio-player


【解决方案1】:

我相信这就是你要找的。​​p>

您应该创建一个状态变量,在本例中为 _index。该值保存当前正在播放的项目的索引。在ListView 小部件的builder 方法中,您可以检查它的索引是否与状态的索引相同。


import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: App()));

class App extends StatefulWidget {
  const App({
    Key? key,
  }) : super(key: key);

  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  /// The song that is currently selected.
  int? _index;

  void _updateSelected(int index) => setState(() => _index = index);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: 10,
      itemBuilder: (context, index) {
        // Check whether the index is the selected index.
        final _isSelected = index == _index;

        return ListTile(
          title: Text('Song title'),
          // Change the icon based on `isSelected`.
          leading: Icon(_isSelected ? Icons.pause : Icons.play_arrow),
          // Call the method when the tile is tapped.
          onTap: () => _updateSelected(index),
        );
      },
    );
  }
}


【讨论】:

    猜你喜欢
    • 2020-02-02
    • 2021-05-07
    • 2019-03-21
    • 2020-05-02
    • 1970-01-01
    • 2014-09-06
    • 2020-12-27
    • 2018-08-25
    • 2022-01-09
    相关资源
    最近更新 更多