Home > Mobile >  why function map return null (null safety?)
why function map return null (null safety?)

Time:03-18

error (The method 'map' can't be uncoditionally invoked because the receiver can be 'null'. The making tha call conitional (using '?') or adding a null check to the target ('!).)

Future<Post> fetchPhotos() async {
  http.Response res =await http.get(Uri.https('jsonplaceholder.typicode.com', 'posts/2'));
  if (res.statusCode == 200) {
      String data = res.body;
      var jsonData = jsonDecode(data); 
      Posts posts = Posts.fromJson(jsonData);
      List<Post> pList = posts.postList.map((e) => Post.fromJson(e)).toList();//
      return posts;
  } else {
      throw Exception("faild to load photos");
  }
}

Model

import 'package:flutter/foundation.dart';

class Post {
final int? userId;
final int? id;
final String? title;
final String? body;
Post({
  @required this.userId,
  @required this.id,
  @required this.title,
  @required this.body,
});

factory Post.fromJson(Map<String, dynamic> jsonData) {
  return Post(
    userId: jsonData["userId"],
    id: jsonData["id"],
    title: jsonData["title"],
    body: jsonData["body"]);
 }
}

class Posts {
  late final List<dynamic>? postList;
  Posts({this.postList});
  factory Posts.fromJson(Map<String, dynamic> jsonData) {
  return Posts(
  postList: jsonData['postList'],
);

} }

CodePudding user response:

add a ! to postList, like this: posts.postList!.map

  • Related