albums.dart 2.4 KB

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