如何在Flutter中读取音频扩展并在ListView中显示?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在Flutter中读取音频扩展并在ListView中显示?相关的知识,希望对你有一定的参考价值。

如何在Flutter中创建一个函数,它将从SD卡读取音频文件并将其显示到ListView

答案

如果你在谈论能够识别文件扩展名,那么首先需要安装Path并导入它:

import 'package:path/path.dart' as p;

然后检查这个:

String _extension = p.extension(_someFile).split('?').first;
另一答案

我建议你阅读Android Studio | Files的文档

  • 您可以使用fileList()来获取ArrayList
  • 此外,使用for循环来获取名称和路径 - > file.getName()| file.getPath()
另一答案

如果您要询问显示音频文件列表 - 这里是我的代码示例:

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_app/storage.dart';
import 'package:path_provider/path_provider.dart';
import 'package:simple_permissions/simple_permissions.dart';

class BrowserScaffold extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _BrowserScaffoldState();
  }
}

class _BrowserScaffoldState extends State<BrowserScaffold> {
  final List<FileSystemEntity> files = List<FileSystemEntity>();
  final savedFiles = Set<File>();
  Directory parent;
  ScrollController controller = ScrollController();

  @override
  Widget build(BuildContext context) {
    if (parent == null) {
      SimplePermissions
          .requestPermission(Permission.WriteExternalStorage)
          .then((value) {
        if (value == PermissionStatus.authorized) {
          localPath.then((String value) {
            Directory dir = Directory(value);
            while (dir.path != dir.parent.path) {
              dir.isAbsolute;
              dir = dir.parent;
            }
            parent = dir;
            setState(() {
              files.addAll(dir.parent.listSync());
              sortFiles();
            });
          });
        } else {
          SimplePermissions.openSettings();
        }
      });
    }
    return Scaffold(
      appBar: AppBar(
        title: Text('Files'),
        actions: <Widget>[
          IconButton(icon: Icon(Icons.check), onPressed: apply),
        ],
      ),
      body: buildList(),
    );
  }

  void sortFiles() {
    for (int i = files.length - 1; i >= 0; i--) {
      FileSystemEntity entity = files[i];
      if (entity is Link) {
        files.remove(entity);
      } else if (entity is Directory) {
        try {
          entity.listSync();
        } catch (ex) {
          print('catch: ${entity.path}, $ex');
          files.remove(entity);
        }
      }
    }
    files.sort((FileSystemEntity a, FileSystemEntity b) {
      if (a is Directory && b is File) return -1;
      if (a is File && b is Directory) return 1;
      return a.path.compareTo(b.path);
    });
  }

  Widget buildList() {
    if (parent == null) return ListView();
    bool isRoot = parent.path == parent.parent.path;
    return ListView.builder(
      itemBuilder: (context, i) {
        if (i.isOdd)
          return Divider(
            height: 4.0,
          );
        final index = isRoot ? i ~/ 2 : i ~/ 2 - 1;
        return buildRow(index);
      },
      itemCount: isRoot ? files.length * 2 : (files.length + 1) * 2,
      controller: controller,
    );
  }

  Widget buildRow(int index) {
    if (index == -1) return getRootTile();
    FileSystemEntity file = files[index];

    if (file is Directory) return getDirectoryTile(file);
    if (file is File) return getFileTile(file);
    if (file is Link)
      return Container(
        height: 0.0,
      );
    return Container(
      height: 0.0,
    );
  }

  Widget getRootTile() {
    return ListTile(
      title: Text('../'),
      trailing: Icon(Icons.keyboard_backspace),
      onTap: () {
        setState(() {
          parent = parent.parent;
          List<FileSystemEntity> rootList = parent.listSync();
          files.clear();
          files.addAll(rootList);
          sortFiles();
        });
      },
    );
  }

  Widget getDirectoryTile(Directory dir) {
    return ListTile(
      title: Text(dir.path.split('/').last),
      trailing: Icon(
        Icons.folder_open,
        color: Colors.grey,
      ),
      onTap: () {
        setState(() {
          parent = dir;
          files.clear();
          files.addAll(dir.listSync());
          sortFiles();
        });
      },
    );
  }

  Widget getFileTile(File file) {
    bool isSaved = savedFiles.map((file) => file.path).contains(file.path);
    final List<String> extensions = <String>[
      "MP3",
      "WAV",
      "AAC",
      "WMA",
      "AMR",
      "OGG",
      "MIDI"
    ];
    bool isRightType =
        extensions.contains(file.path.split('.').last.toUpperCase());
    return ListTile(
      title: Text(file.path.split('/').last),
      trailing: isRightType
          // ignore: missing_required_param
          ? IconButton(
              icon: Icon(
                isSaved ? Icons.check_box : Icons.check_box_outline_blank,
                color: isSaved ? Colors.blueGrey : Colors.grey,
              ),
            )
          : null,
      onTap: () {
        setState(() {
          if (isSaved) {
            savedFiles.remove(file);
          } else {
            savedFiles.add(file);
          }
        });
      },
    );
  }

  void apply() async {
    final List<Track> list = List();
    list.addAll(savedFiles.map((file) => Track(file.path)));
    Navigator.of(context).pop(list);
  }

  Future<String> get localPath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }
}

在我的情况下,我显示所有文件,但只能选择音频(带复选框)

以上是关于如何在Flutter中读取音频扩展并在ListView中显示?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Flutter Firestore 中读取数组的 FieldValues

Flutter:如何知道列表视图中的项目位置?

使用扩展音频文件服务 (ExtAudioFileRead) 读取音频

读取其他应用在后台播放的音频输出

Flutter中将ListView Builder的索引增加2

如何获取音频文件的长度而不在 Flutter/Dart 中播放