finnow/flutter_app/lib/api/profile.dart

32 lines
897 B
Dart

import 'dart:convert';
import 'package:http/http.dart' as http;
class Profile {
final String name;
const Profile(this.name);
factory Profile.fromJson(Map<String, dynamic> json) {
return switch(json) {
{'name': String name} => Profile(name),
_ => throw const FormatException('Invalid profile object.')
};
}
}
Future<List<Profile>> getProfiles(String token) async {
final http.Response response = await http.get(
Uri.parse('http://localhost:8080/api/profiles'),
headers: {
'Authorization': 'Bearer $token'
}
);
if (response.statusCode == 200) {
if (jsonDecode(response.body) == null) return []; // Workaround for bad array serialization in the API.
final data = jsonDecode(response.body) as List<dynamic>;
return data.map((obj) => Profile.fromJson(obj)).toList();
} else {
throw Exception('Failed to get profiles.');
}
}