I try to get a list of youtube categories with flutter. But i get this message all the time. I’m not very good with models and factory’s yet so i hope you can point in the right direction.
This is my model:
class YoutubeCategory {
String? catagoryId;
String catagoryName;
String catagoryPosterUrl;
String catagoryPostDate;
YoutubeCategory(
{required this.catagoryId,
required this.catagoryName,
required this.catagoryPostDate,
required this.catagoryPosterUrl});
factory YoutubeCategory.fromJson(Map<String, dynamic> json) =>
YoutubeCategory(
catagoryId: json['snippet']['channelId'],
catagoryName: json['snippet']['title'],
catagoryPostDate: json['snippet']['publishedAt'],
catagoryPosterUrl: json['snippet']['thumbnails']['maxres']['url'],
);
}
And this is the Future:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../models/youtube_category.dart';
class YoutubeProvider with ChangeNotifier {
List<YoutubeCategory> _youtubeCategories = [];
Future<void> categoryFetchAndSet() async {
try {
final url = Uri.parse(
'https://youtube.googleapis.com/youtube/v3/playlists?part=snippet&channelId=....');
final response = await http.get(url);
final items = json.decode(response.body);
final extractedData = items as Map<String, dynamic>;
extractedData.forEach((key, value) =>
print(value['items']['snippet']['publishedAt']));
} catch (error) {
print(error);
}
}
}
And this is the json created from Youtube Api:
{
"kind": "youtube#playlistListResponse",
"etag": "mtkdrKhMOsTic_dFeZqG3aYubA8",
"nextPageToken": "CAEQAA",
"pageInfo": {
"totalResults": 19,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#playlist",
"etag": "o5B4L3KrFUAQo1NAlED4UPocd8M",
"id": "PLiwjE2lUypAnz5SFxg4gVLvc5rETpC7rX",
"snippet": {
"publishedAt": "2022-03-08T11:28:10Z",
"channelId": "UCxlSClyfAZM3ZY9ibKDlFDA",
"title": "Minibieb On Tour",
"description": "",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/TItFjTidN8k/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/TItFjTidN8k/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/TItFjTidN8k/hqdefault.jpg",
"width": 480,
"height": 360
},
"standard": {
"url": "https://i.ytimg.com/vi/TItFjTidN8k/sddefault.jpg",
"width": 640,
"height": 480
},
"maxres": {
"url": "https://i.ytimg.com/vi/TItFjTidN8k/maxresdefault.jpg",
"width": 1280,
"height": 720
}
},
"channelTitle": "Title",
"localized": {
"title": "Minibieb On Tour",
"description": ""
}
}
}
]
}
It’s complex json i guess not sure if my model is ok.
3
Answers
One of value you’re trying to save in the variable type
String
is actuallyint
, recheck the response of the API, or can you please post the test response to validate?Put your response of the API into here and make model and use that model in app instead of making custom models.
Response for
"items"
is a Listto print items do as following