so It's my first time using API on flutter I just take the tutorial copy paste and change some line for the test I just want to learn more about API's so don't blame me if I made a dumb mistake or something like . I try to get a title from the APi and get this error if somoene can help that will be really great.
Future<Album> fetchAlbum() async {
final response = await http
.get(Uri.parse('https://api.mangadex.org/manga'));
if (response.statusCode == 200) {
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load album');
}
}
class Album {
final int year;
final String title;
const Album({
required this.year,
required this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
year: json['year'],
title: json['title'],
);
}
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
@override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.title);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
CodePudding user response:
actually what goes wrong here is that json response you are getting back from the API doesn't contain a year or title fields. So, both json['year'] and json['title'] will be null. And since you are assigning them to Album.year and Album.title which are not nullable, the whole app breaks.
I tried calling the API URI, and found that the JSON structure is a bit different.
You might wan this code for your fromJson method for it to work.
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
year: json['data'][0]['attributes']['year'],
title: json['data'][0]['attributes']['title']["en"],
);
}
Please note that json['data'] is actually an array of albums, in this code we're just fetching ONLY the first element inside that array.
CodePudding user response:
If I understand what you're going for, you should call fetchAlbum() instead of using futureAlbum in the FutureBuilder since the fetchAlbum() method is a Future that returns the album info. The call of futureAlbum = fetchAlbum() in initState doesn't fetch the album info in a manner that's useable, there's a way to do it, but it's complicated and not needed since you're already using the FutureBuilder.
