I am trying to fetch the JSON from https://jsonplaceholder.typicode.com/photos/ but getting error like Unhandled Exception: type 'List' is not a subtype of type 'Map<String, dynamic>'. I am still a learning flutter.
Any fixes?
Here is my code.
main.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' show get;
import 'src/widgets/image_list.dart';
import 'src/models/imageloader.dart';
void main() {
runApp(App());
}
class App extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
title: "app",
theme: ThemeData(primarySwatch: Colors.blue),
home: homePage(),
);
}
}
class homePage extends StatefulWidget {
@override
_homePageState createState() => _homePageState();
}
class _homePageState extends State<homePage> {
int counter = 0;
List<ImageLoader> images = [];
void loadImage() async {
counter++;
var response =
await get(Uri.parse('https://jsonplaceholder.typicode.com/photos/'));
var imageModel = ImageLoader.fromJson(jsonDecode(response.body));
/* var imagemodel = imageModel.map((i) => ImageLoader.fromJson(i)).toList(); */
setState(() {
images.add(imageModel);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Let's load some images"),
),
floatingActionButton: FloatingActionButton(
onPressed: loadImage,
child: Icon(Icons.add),
),
body: ImageList(images),
);
}
}
imageLoager.dart
class ImageLoader {
int id = 0;
String url = "";
String title = "";
ImageLoader(this.id, this.url, this.title);
ImageLoader.fromJson(Map<String, dynamic> parsedJson) {
id = parsedJson['id'];
url = parsedJson['url'];
title = parsedJson['title'];
}
}
image_list.dart
import 'package:flutter/material.dart';
import '../models/imageloader.dart';
class ImageList extends StatelessWidget {
final List<ImageLoader> images;
ImageList(
this.images,
);
Widget build(BuildContext context) {
return ListView.builder(
itemCount: images.length,
itemBuilder: (context, int index) {
return Text(images[index].url);
},
);
}
}
Debug Console:
Unhandled Exception: type 'List' is not a subtype of type 'Map<String, dynamic>'
E/flutter ( 4984): #0 _homePageState.loadImage
package:imageloader/main.dart:33
E/flutter ( 4984):
E/flutter ( 4984):