songs.dart 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import 'dart:convert';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter/widgets.dart';
  4. import 'package:http/http.dart' as http;
  5. import '../types/song.dart';
  6. import '../utils/url.dart';
  7. import './spinner.dart';
  8. Future<List<Song>> fetchSongs(String apiUrl, String artist) async {
  9. final response = await http.get(formattedUrl(apiUrl, '/songs', {
  10. 'artist': artist,
  11. }));
  12. if (response.statusCode != 200) {
  13. throw Exception('Failed to load songs');
  14. }
  15. List<Song> songs = [];
  16. var responseJson = jsonDecode(response.body)['songs'];
  17. for (var i = 0; i < responseJson.length; i++) {
  18. songs.add(Song.fromJson(responseJson[i]));
  19. }
  20. return songs;
  21. }
  22. class Songs extends StatelessWidget {
  23. final String artist;
  24. final String album;
  25. final Future<List<Song>> songs;
  26. final void Function(int) onSelect;
  27. Songs({
  28. @required this.artist, // can be an empty string
  29. @required this.album, // can be an empty string
  30. @required this.songs,
  31. @required this.onSelect,
  32. });
  33. @override
  34. Widget build(BuildContext context) {
  35. if (artist == null || songs == null) {
  36. return Container();
  37. }
  38. return FutureBuilder<List<Song>>(
  39. future: songs,
  40. builder: (context, snapshot) {
  41. if (snapshot.hasData) {
  42. var filteredAlbums = this.album == null
  43. ? snapshot.data
  44. : snapshot.data.where((song) => song.album == this.album);
  45. return ListView(
  46. padding: EdgeInsets.only(left: 8, right: 8),
  47. children: filteredAlbums.map<Widget>((song) => Container(
  48. height: 40,
  49. color: Colors.white,
  50. child: Align(
  51. alignment: Alignment.centerLeft,
  52. child: TextButton(
  53. child: Text("${song.track} - ${song.title.length == 0 ? 'Untitled Track' : song.title}"),
  54. onPressed: () {
  55. onSelect(song.id);
  56. },
  57. style: TextButton.styleFrom(
  58. textStyle: TextStyle(fontSize: 18, fontStyle: FontStyle.normal),
  59. primary: Colors.black,
  60. ),
  61. ),
  62. ),
  63. )).toList(),
  64. );
  65. }
  66. if (snapshot.hasError) {
  67. return Text("${snapshot.error}");
  68. }
  69. return CenterSpinner();
  70. },
  71. );
  72. }
  73. }