I want to display the api data as a list and add an Inkwell with onTap where every time the user clicks on an item, data is displayed in another class, but I get an error at line 42 in main dart the error
List resData = snapshot.data;
The code just loads but doesn't display anything from the api.
I use api album form flutter
the main
import 'dart:async';
import 'package:flutter/material.dart';
import 'data/functions.dart';
import 'album.dart';
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) {
List resData = snapshot.data;
return ListView.builder(
itemCount: resData.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(title: Text(resData[index]["title"]),),
);
});
}
// if (snapshot.hasData) {
// return Text(snapshot.data!.title);
// } else if (snapshot.hasError) {
// return Text('${snapshot.error}');
// }
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);
}
}
The functions dart
import 'dart:convert';
import 'package:gamess/album.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
final response = await http
.get(Uri.parse('https://jsonplaceholder.typicode.com/albums'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
the album dart
class Album {
final int userId;
final int id;
final String title;
Album({
required this.userId,
required this.id,
required this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}
CodePudding user response:
Ok, first you recieve from API a list of Albums and you are trying to parse a list of Albums into a single Album with the fromJson. To fix this, change the code from functions.dart
to this.
`
import 'dart:convert';
import '../album.dart';
import 'package:http/http.dart' as http;
Future<List<Album>> fetchAlbum() async {
final response =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
List<Album> albums = [];
List<dynamic> albumsJson = jsonDecode(response.body);
albumsJson.forEach(
(oneAlbum) {
Album album = Album.fromJson(oneAlbum);
albums.add(album);
},
);
return albums;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
`
Second thing is now that you are receiving the data properly lets fix the ui, you can't call a Future without await and you can't call a await on init, so a removed the late Future<Album> futureAlbum;
and the futureAlbum = fetchAlbum();
;
Next you have to adapt the future call on the future builder, changing the future: futureAlbum,
to future: fetchAlbum(),
;
Now that you know you're receiving a List you have to define that on the Future builder.
Any questions just ask, the main.dart
file is below:
`
import 'package:flutter/material.dart';
import 'data/functions.dart';
import 'album.dart';
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> {
@override
void initState() {
super.initState();
}
@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<List<Album>>(
future: fetchAlbum(),
builder: (context, snapshot) {
if (snapshot.hasData) {
List<Album>? resData = snapshot.data;
return ListView.builder(
itemCount: resData != null ? resData.length : 0,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(resData?[index].title ?? ""),
),
);
});
}
// if (snapshot.hasData) {
// return Text(snapshot.data!.title);
// } else if (snapshot.hasError) {
// return Text('${snapshot.error}');
// }
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);
}
}
`