KikiDiki
KikiDiki

Reputation: 31

How do I display name (without extension) of files from assets folders in flutter

I have some music files in my assets folder and I want to automatically display them in a list, without having to write a line for every single music in the folder.

like this

I think something like ListView.builder might work, but I'm pretty new in all this and not quite sure how to execute this properly.

Upvotes: 0

Views: 417

Answers (1)

Bach
Bach

Reputation: 3326

Since it's impossible to get the names of your music files from the /assets folder within a Flutter project, I think you can try these ways:

  • Have a json file listing all the metadata of the files (name, artist, path in /assets, etc) and work with that file (get the name, get the path of the file, etc).
  • Store your music online and get them through APIs
  • Copy all the music from your /assets into a phone's directory, then handle the files from that directory from now on (For example: Call this method to get the names of the files). Check out this answer.

If what you want to display is like the image you describe, and if the name is not important (like ringtones), then you can simply do this (assuming you name the files by numbers from 1-10):

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: SampleScreen(),
  ));
}

class SampleScreen extends StatefulWidget {
  @override
  _SampleScreenState createState() => _SampleScreenState();
}

class _SampleScreenState extends State<SampleScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
          itemCount: 10,
          itemBuilder: (context, index) => _buildMusicItem(index)),
    );
  }

  Widget _buildMusicItem(int index) {
    return Container(
      height: 40,
      margin: EdgeInsets.all(5),
      padding: EdgeInsets.only(left: 10),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          border: Border.all(color: Colors.red, width: 2)),
      alignment: Alignment.centerLeft,
      child: Text('Music ${index + 1}'),
    );
  }
}

Result:

enter image description here

Upvotes: 1

Related Questions