albums.dart 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 '../utils/url.dart';
  6. import './spinner.dart';
  7. Future<List<String>> fetchAlbums(String apiUrl, String artist) async {
  8. final response = await http.get(formattedUrl(apiUrl, '/albums', {
  9. 'artist': artist,
  10. }));
  11. if (response.statusCode == 200) {
  12. return List<String>.from(jsonDecode(response.body)['albums']);
  13. } else {
  14. throw Exception('Failed to load albums');
  15. }
  16. }
  17. const allAlbums = 'All albums';
  18. class Albums extends StatelessWidget {
  19. final String artist;
  20. final Future<List<String>> albums;
  21. final void Function(String, String) onSelect;
  22. Albums({
  23. @required this.artist,
  24. @required this.albums,
  25. @required this.onSelect,
  26. });
  27. @override
  28. Widget build(BuildContext context) {
  29. if (artist == null || albums == null) {
  30. return Container();
  31. }
  32. return FutureBuilder<List<String>>(
  33. future: albums,
  34. builder: (context, snapshot) {
  35. if (snapshot.hasData) {
  36. List<String> albumsWithAll = snapshot.data.sublist(0);
  37. albumsWithAll.insert(0, allAlbums);
  38. return ListView(
  39. padding: EdgeInsets.only(left: 8, right: 8),
  40. children: albumsWithAll.map((album) => Container(
  41. height: 40,
  42. color: Colors.white,
  43. child: Align(
  44. alignment: Alignment.centerLeft,
  45. child: TextButton(
  46. child: Text(album.length == 0 ? 'Unknown album' : album),
  47. onPressed: () {
  48. onSelect(artist, album == allAlbums ? null : album);
  49. },
  50. style: TextButton.styleFrom(
  51. textStyle: TextStyle(fontSize: 18, fontStyle: FontStyle.normal),
  52. primary: Colors.black,
  53. ),
  54. ),
  55. ),
  56. )).toList(),
  57. );
  58. }
  59. if (snapshot.hasError) {
  60. return Text("${snapshot.error}");
  61. }
  62. return CenterSpinner();
  63. },
  64. );
  65. }
  66. }