Необработанное исключение: NoSuchMethodError: метод 'map' был вызван для нуля - PullRequest
0 голосов
/ 28 октября 2019

Я пытаюсь включить карты Google и размещает API в моем проекте. Однако я пришел к ошибке, и я полностью застрял. Я довольно нов, когда дело доходит до десериализации объектов JSON, поэтому, пожалуйста, потерпите меня. У меня есть файл placedetails.json

{
   "html_attributions" : [],
   "result" : {
      "formatted_address" : "198 J. Elizalde, Paranaque City, 1700 Metro Manila, Philippines",
      "formatted_phone_number" : "(02) 8801 8553",
      "name" : "The Diabetes Store",
      "opening_hours" : {
         "open_now" : true,
         "periods" : [
            {
               "close" : {
                  "day" : 0,
                  "time" : "1800"
               },
               "open" : {
                  "day" : 0,
                  "time" : "0900"
               }
            },
            {
               "close" : {
                  "day" : 1,
                  "time" : "1800"
               },
               "open" : {
                  "day" : 1,
                  "time" : "0900"
               }
            },
            {
               "close" : {
                  "day" : 2,
                  "time" : "1800"
               },
               "open" : {
                  "day" : 2,
                  "time" : "0900"
               }
            },
            {
               "close" : {
                  "day" : 3,
                  "time" : "1800"
               },
               "open" : {
                  "day" : 3,
                  "time" : "0900"
               }
            },
            {
               "close" : {
                  "day" : 4,
                  "time" : "1800"
               },
               "open" : {
                  "day" : 4,
                  "time" : "0900"
               }
            },
            {
               "close" : {
                  "day" : 5,
                  "time" : "1800"
               },
               "open" : {
                  "day" : 5,
                  "time" : "0900"
               }
            },
            {
               "close" : {
                  "day" : 6,
                  "time" : "1800"
               },
               "open" : {
                  "day" : 6,
                  "time" : "0900"
               }
            }
         ],
         "weekday_text" : [
            "Monday: 9:00 AM – 6:00 PM",
            "Tuesday: 9:00 AM – 6:00 PM",
            "Wednesday: 9:00 AM – 6:00 PM",
            "Thursday: 9:00 AM – 6:00 PM",
            "Friday: 9:00 AM – 6:00 PM",
            "Saturday: 9:00 AM – 6:00 PM",
            "Sunday: 9:00 AM – 6:00 PM"
         ]
      },
      "rating" : 4.5,
      "reviews" : [
         {
            "author_name" : "Vaughne Ryan",
            "author_url" : "https://www.google.com/maps/contrib/117052285220893351699/reviews",
            "language" : "en",
            "profile_photo_url" : "https://lh5.ggpht.com/-9lQYh-gblhc/AAAAAAAAAAI/AAAAAAAAAAA/SwueUQz5A68/s128-c0x00000000-cc-rp-mo-ba4/photo.jpg",
            "rating" : 3,
            "relative_time_description" : "a month ago",
            "text" : "Nice store for those who doesn't like sweets.",
            "time" : 1568635688
         },
         {
            "author_name" : "Chrystal Marilag",
            "author_url" : "https://www.google.com/maps/contrib/113429222554258141037/reviews",
            "language" : "en",
            "profile_photo_url" : "https://lh4.ggpht.com/-Z6mnd_RHJ6g/AAAAAAAAAAI/AAAAAAAAAAA/NqnSwwtCE0k/s128-c0x00000000-cc-rp-mo/photo.jpg",
            "rating" : 5,
            "relative_time_description" : "5 months ago",
            "text" : "affordable meters and strips, and yummy food items! nutritionist on duty is very accommodating",
            "time" : 1559187949
         },
         {
            "author_name" : "april ladores",
            "author_url" : "https://www.google.com/maps/contrib/107742505451701380528/reviews",
            "language" : "en",
            "profile_photo_url" : "https://lh5.ggpht.com/-SQkcRA8pmHE/AAAAAAAAAAI/AAAAAAAAAAA/v9D_QCobYoU/s128-c0x00000000-cc-rp-mo/photo.jpg",
            "rating" : 5,
            "relative_time_description" : "a year ago",
            "text" : "They were very accomodating and nice.",
            "time" : 1518075466
         },
         {
            "author_name" : "Jane Po",
            "author_url" : "https://www.google.com/maps/contrib/114853608333620212548/reviews",
            "profile_photo_url" : "https://lh3.ggpht.com/-tXHMiwFmkEs/AAAAAAAAAAI/AAAAAAAAAAA/sb_1cmQmKEg/s128-c0x00000000-cc-rp-mo-ba2/photo.jpg",
            "rating" : 5,
            "relative_time_description" : "2 years ago",
            "text" : "",
            "time" : 1504537287
         }
      ],
      "vicinity" : "198 J. Elizalde, Paranaque City",
      "website" : "http://www.thediabetesstore.com.ph/"
   },
   "status" : "OK"
}

И я создал файл placedetails_model.dart, чтобы поместить необходимую мне информацию в модель данных, которую я определил здесь:

class PlaceDetails {
  String address;
  String phoneNumber;
  String name;
  OpeningHours openinghours;
  double rating;
  List<Reviews> reviews;
  String vicinity;
  String website;

  PlaceDetails(
      {this.address,
      this.phoneNumber,
      this.name,
      this.openinghours,
      this.rating,
      this.reviews,
      this.vicinity,
      this.website});

  factory PlaceDetails.fromJson(Map<String, dynamic> parsedJson) {
    var list = parsedJson['reviews'] as List;
    List<Reviews> reviews = list.map((i) => Reviews.fromJson(i)).toList();

    return PlaceDetails(
        address: parsedJson['formatted_address'],
        name: parsedJson['name'],
        openinghours: OpeningHours.fromJson(parsedJson['opening_hours']),
        phoneNumber: parsedJson['formatted_phone_number'],
        rating: parsedJson['rating'],
        reviews: reviews,
        vicinity: parsedJson['vicinity'],
        website: parsedJson['website']);
  }
}

class OpeningHours {
  bool opennow;
  List<String> weekdayText;
  OpeningHours({this.opennow, this.weekdayText});

  factory OpeningHours.fromJson(Map<String, dynamic> parsedJson) {
    return OpeningHours(
        opennow: parsedJson['open_now'],
        weekdayText: parsedJson['weekday_text']);
  }
}

class Reviews {
  String authorname;
  String authorurl;
  String profilePhoto;
  double rating;
  String timedesc;
  String text;

  Reviews(
      {this.authorname,
      this.authorurl,
      this.profilePhoto,
      this.rating,
      this.timedesc,
      this.text});

  factory Reviews.fromJson(Map<String, dynamic> parsedJson) {
    return Reviews(
      authorname: parsedJson['author_name'],
      authorurl: parsedJson['author_url'],
      profilePhoto: parsedJson['profile_photo_url'],
      rating: parsedJson['rating'],
      timedesc: parsedJson['relative_time_description'],
      text: parsedJson['text'],
    );
  }
}

Пока, это не из живого вызова RESTAPI, я локально загружаю этот .json здесь:

import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
import 'package:flutter_json/model/placedetails_model.dart';

Future<String> _loadPlaceDets() async {
  return await rootBundle.loadString('assets/placedetails.json');
}


Future loadPlaceDetails() async {
  String jsonPlace = await _loadPlaceDets();
  final jsonResponse = json.decode(jsonPlace);
  PlaceDetails place = new PlaceDetails.fromJson(jsonResponse);
  print(place);
}

Моя причина, почему я печатаю место, чтобы увидеть, есть ли уже "Экземпляр"PlaceDetails ". Однако я получаю эту ошибку: «Необработанное исключение: NoSuchMethodError: Метод 'map' был вызван на нуль". Кто-то, пожалуйста, помогите, и я был бы очень признателен за объяснение, почему мой код не работает .. Большое спасибо!

Вот что говорит моя консоль отладки:

E/flutter ( 5354): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: NoSuchMethodError: The method 'map' was called on null.
E/flutter ( 5354): Receiver: null
E/flutter ( 5354): Tried calling: map<Reviews>(Closure: (dynamic) => Reviews)
E/flutter ( 5354): #0      Object.noSuchMethod  (dart:core-patch/object_patch.dart:51:5)
E/flutter ( 5354): #1      new PlaceDetails.fromJson 
package:flutter_json/model/placedetails_model.dart:23
E/flutter ( 5354): #2      loadPlaceDetails 
package:flutter_json/services/placedetails_services.dart:14
E/flutter ( 5354): <asynchronous suspension>
E/flutter ( 5354): #3      main 
package:flutter_json/main.dart:21
E/flutter ( 5354): #4      _runMainZoned.<anonymous closure>.<anonymous closure>  (dart:ui/hooks.dart:229:25)
E/flutter ( 5354): #5      _rootRun  (dart:async/zone.dart:1124:13)
E/flutter ( 5354): #6      _CustomZone.run  (dart:async/zone.dart:1021:19)
E/flutter ( 5354): #7      _runZoned  (dart:async/zone.dart:1516:10)
E/flutter ( 5354): #8      runZoned  (dart:async/zone.dart:1500:12)

1 Ответ

1 голос
/ 28 октября 2019

Я думаю, что вы забыли часть .result, может быть, она должна быть parsedJson['result']['reviews']?

...