Please help converting Model to JSON

3,257 views
Skip to first unread message

Fer Buero Trebino

unread,
May 25, 2020, 9:51:55 AM5/25/20
to Flutter Development (flutter-dev)
Hello everyone, I've been dealing with this problem for a couple of days, I search everywhere to find a solution but it was no possible to fix it.

I have a nested Model Class(Business Model) that I need to POST to an API, but when I'm trying to do businessModelToJson    the next error message appears:

Exception has occurred.
NoSuchMethodError (NoSuchMethodError: The method 'map' was called on null. Receiver: null Tried calling: map<dynamic>(Closure: (Hour) => Map<String, dynamic>))

Here is my model Class, I tried to specify Map<String,dynamic> in:
        hours: List<Hour>.from(json["hours"].map((x) => Hour.fromJson(x))),

and also in "timeWindows" , but I keep getting the same error.

import 'dart:convert';

BusinessModel businessModelFromJson(String str) =>
    BusinessModel.fromJson(json.decode(str));

String businessModelToJson(BusinessModel data) => json.encode(data.toJson());

class BusinessModel {
  String categoryId;
  List<Hour> hours;
  String image;
  List<String> labels;
  Location location;
  String name;
  String subCategoryId;
  String taxId;
  String website;

  BusinessModel({
    this.categoryId,
    this.hours,
    this.image,
    this.labels,
    this.location,
    this.name,
    this.subCategoryId,
    this.taxId,
    this.website,
  });

  factory BusinessModel.fromJson(Map<Stringdynamic> json) => BusinessModel(
        categoryId: json["categoryId"],
        hours: List<Hour>.from(json["hours"].map((x) => Hour.fromJson(x))),
        image: json["image"],
        labels: List<String>.from(json["labels"].map((x) => x)),
        location: Location.fromJson(json["location"]),
        name: json["name"],
        subCategoryId: json["subCategoryId"],
        taxId: json["taxId"],
        website: json["website"],
      );

  Map<StringdynamictoJson() => {
        "categoryId": categoryId,
        "hours"List<dynamic>.from(hours.map((x) => x.toJson())),
        "image": image,
        "labels"List<dynamic>.from(labels.map((x) => x)),
        "location": location.toJson(),
        "name": name,
        "subCategoryId": subCategoryId,
        "taxId": taxId,
        "website": website,
      };
}

class Hour {
  String dayOfWeek;
  List<TimeWindow> timeWindow;
  List<TimeWindow> timeWindows;

  Hour({
    this.dayOfWeek,
    this.timeWindow,
    this.timeWindows,
  });

  factory Hour.fromJson(Map<Stringdynamic> json) => Hour(
        dayOfWeek: json["dayOfWeek"],
        timeWindow: List<TimeWindow>.from(
            json["timeWindow"].map((x) => TimeWindow.fromJson(x))),
        timeWindows: List<TimeWindow>.from(
            json["timeWindows"].map((x) => TimeWindow.fromJson(x))),
      );

  Map<StringdynamictoJson() => {
        "dayOfWeek": dayOfWeek,
        "timeWindow"List<TimeWindow>.from(timeWindow.map((x) => x.toJson())),
        "timeWindows":
            List<TimeWindow>.from(timeWindows.map((x) => x.toJson())),
      };
}

class TimeWindow {
  String from;
  String to;

  TimeWindow({
    this.from,
    this.to,
  });

  factory TimeWindow.fromJson(Map<Stringdynamic> json) => TimeWindow(
        from: json["from"],
        to: json["to"],
      );

  Map<StringdynamictoJson() => {
        "from": from,
        "to": to,
      };
}

class Location {
  String address;
  int latitude;
  int longitude;

  Location({
    this.address,
    this.latitude,
    this.longitude,
  });

  factory Location.fromJson(Map<Stringdynamic> json) => Location(
        address: json["address"],
        latitude: json["latitude"],
        longitude: json["longitude"],
      );

  Map<StringdynamictoJson() => {
        "address": address,
        "latitude": latitude,
        "longitude": longitude,
      };
}



I created this model class to JSON using https://app.quicktype.io/

Does anyone have an idea where is the problem?

Thanks in advance,
Fer

Suzuki Tomohiro

unread,
May 25, 2020, 10:04:19 AM5/25/20
to Flutter Development (flutter-dev)
Your code tried calling: map<dynamic>(Closure: (Hour) => Map<String, dynamic>))
but the “hours” was null. Set conditional breakpoint at that line with condition hours==null. You’ll find why it was null.

Very likely you want to set default value for “hours” as a empty list, not null.


--
You received this message because you are subscribed to the Google Groups "Flutter Development (flutter-dev)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/flutter-dev/e7af5689-55ee-48cd-93e4-596210584b4f%40googlegroups.com.

Fer Buero Trebino

unread,
May 25, 2020, 10:51:19 AM5/25/20
to Flutter Development (flutter-dev)
Thanks, Suzuki! I realized that I was sending the incorrect object.

Now I'm sending the correct information and I can check that the object is filled with the data (Attached Captura.PNG)

But I'm still having an error
Exception has occurred.
_TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>')


I search a lot about this problem, and the closest thing I found is that using automatic parsed JSON (like me using https://app.quicktype.io/) creates this error, I checked my model class in detail, but I can't found what is causisng the problem.



To unsubscribe from this group and stop receiving emails from it, send an email to flutt...@googlegroups.com.
Captura.PNG

Suzuki Tomohiro

unread,
May 25, 2020, 4:05:58 PM5/25/20
to Flutter Development (flutter-dev)
Do you want to share the entire stacktrace and source code with line number?


To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/flutter-dev/f1bfcffb-82f8-4600-be8d-77f3c24ffd68%40googlegroups.com.

Fer Buero Trebino

unread,
May 25, 2020, 5:14:51 PM5/25/20
to Flutter Development (flutter-dev)
Thanks again Suzuki, I hope this is what you asked:

E/flutter (20350): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Map<String, String>'
E/flutter (20350): #0 BusinessService.createBusiness
package:app_pickolo_manager/…/services/business_service.dart:58
E/flutter (20350): #1 CreateBusinessPage02.build.<anonymous closure>
package:app_pickolo_manager/…/create_business/create_business_02.dart:85
E/flutter (20350): #2 CreateBusinessPage02.build.<anonymous closure>
package:app_pickolo_manager/…/create_business/create_business_02.dart:79
E/flutter (20350): #3 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:779
E/flutter (20350): #4 _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:862
E/flutter (20350): #5 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:182
E/flutter (20350): #6 TapGestureRecognizer.handleTapUp
package:flutter/…/gestures/tap.dart:504
E/flutter (20350): #7 BaseTapGestureRecognizer._checkUp
package:flutter/…/gestures/tap.dart:282
E/flutter (20350): #8 BaseTapGestureRecognizer.handlePrimaryPointer
package:flutter/…/gestures/tap.dart:217
E/flutter (20350): #9 PrimaryPointerGestureRecognizer.handleEvent
package:flutter/…/gestures/recognizer.dart:475
E/flutter (20350): #10 PointerRouter._dispatch
package:flutter/…/gestures/pointer_router.dart:76
E/flutter (20350): #11 PointerRouter._dispatchEventToRoutes.<anonymous closure>
package:flutter/…/gestures/pointer_router.dart:122
E/flutter (20350): #12 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter (20350): #13 PointerRouter._dispatchEventToRoutes
package:flutter/…/gestures/pointer_router.dart:120
E/flutter (20350): #14 PointerRouter.route
package:flutter/…/gestures/pointer_router.dart:106
E/flutter (20350): #15 GestureBinding.handleEvent
package:flutter/…/gestures/binding.dart:218
E/flutter (20350): #16 GestureBinding.dispatchEvent
package:flutter/…/gestures/binding.dart:198
E/flutter (20350): #17 GestureBinding._handlePointerEvent
package:flutter/…/gestures/binding.dart:156
E/flutter (20350): #18 GestureBinding._flushPointerEventQueue
package:flutter/…/gestures/binding.dart:102
E/flutter (20350): #19 GestureBinding._handlePointerDataPacket
package:flutter/…/gestures/binding.dart:86
E/flutter (20350): #20 _rootRunUnary (dart:async/zone.dart:1196:13)
E/flutter (20350): #21 _CustomZone.runUnary (dart:async/zone.dart:1085:19)
E/flutter (20350): #22 _CustomZone.runUnaryGuarded (dart:async/zone.dart:987:7)
E/flutter (20350): #23 _invoke1 (dart:ui/hooks.dart:275:10)
E/flutter (20350): #24 _dispatchPointerDataPacket (dart:ui/hooks.dart:184:5)
E/flutter (20350):

Here is the onpressed, where I call the business service and I send the BusinessModel.


                    onPressed: () async {

                      final businessService = new BusinessService();

                      final info = await businessService.createBusiness(businessProvider.businessModel);

                      if (info['ok']) {
                        Navigator.pushReplacementNamed(context, 'home');
                      } else {
                        showAlertMessage(context, info['message']);
                      }
                      print(
                          'pr: ${businessModelToJson(businessProvider.businessModel)}');
                    },

And here is the Business Service where I make the API call

Future<Map<Stringdynamic>> createBusiness(userModel) async {
    final headers = {
      'Api-Token''xxxxxxxxxxxxxxxx',
      'Session-Token': _prefs.sessionId,
      'Content-Type''application/json'
    };


    final resp = await http.post(
      url,
      body: businessModelToJson(userModel),
      headers: headers,
    );

    final decodedData = json.decode(resp.body);

    print(decodedData);

    if (resp.statusCode == 200) {
      _prefs.sessionId = decodedData.toString();

      return {'ok'true'businessId': decodedData};
    } else {
      Map<Stringdynamic> decodedResp = json.decode(resp.body);

      return {'ok'false'message': decodedResp['message'].toString()};
    }
  }

lastly a small sample of my businessProvider

class BusinessProvider extends ChangeNotifier {

  BusinessModel businessModel = BusinessModel();

    void updateName(String nameChange) {
    businessModel.name = nameChange;
    notifyListeners();
  }


Message has been deleted

Neil J. Warner

unread,
May 25, 2020, 6:57:49 PM5/25/20
to Flutter Development (flutter-dev)
I strongly advise quicktype.io for simple json parsing code for dart/flutter. Works awesome with json of any nesting and complexity.

Even if you solved that part of you problem this may benefit someone else that sees this thread
Thanks

Suzuki Tomohiro

unread,
May 25, 2020, 9:05:49 PM5/25/20
to Fer Buero Trebino, Flutter Development (flutter-dev)

Benedicte Roussel

unread,
May 25, 2020, 9:06:32 PM5/25/20
to Flutter Development (flutter-dev), Fer Buero Trebino

class Hour {
  String dayOfWeek;
  List<TimeWindow> timeWindow;
  List<TimeWindow>  timeWindows;

  Hour({
    this.dayOfWeek,
    this.timeWindow,
    this.timeWindows,
  });

Maybe I am totally wrong but reading your code the type String in your class Hour appears to me quite squint. Why not int????

and sorry if I am completely mistaken 
Le lundi 25 mai 2020 à 23:21:19 UTC+2, Fer Buero Trebino <ferbuer...@gmail.com> a écrit :


I think my last message get bad formatted, let me know if you need anything else. Thanks!

here is the onPresssed

                    onPressed: () async {
                      _validateAndSave(context, businessProvider);

                      final businessService = new BusinessService();

                      final info = await businessService
                          .createBusiness(businessProvider.businessModel);

                      if (info['ok']) {
                        Navigator.pushReplacementNamed(context, 'home');
                      } else {
                        showAlertMessage(context, info['message']);
                      }

                      print(
                          'pr: ${businessModelToJson(businessProvider.businessModel)}');
                    },



/////////////HERE THE SERVICE

Future<Map<Stringdynamic>> createBusiness(userModel) async {
    final headers = {
      'Api-Token''kxgnFSZQk93qWdPaN0kdMuHXxSfL7DTEQ1V6AhtH',
      'Session-Token': _prefs.sessionId,
      'Content-Type''application/json'
    };


    final resp = await http.post(
      url,
      body: businessModelToJson(userModel),
      headers: headers,
    );

    final decodedData = json.decode(resp.body);

    print(decodedData);

    if (resp.statusCode == 200) {
      _prefs.sessionId = decodedData.toString();

      return {'ok'true'businessId': decodedData};
    } else {
      Map<Stringdynamic> decodedResp = json.decode(resp.body);

      print(decodedResp);

      return {'ok'false'message': decodedResp['message'].toString()};
    }
  }


//// AND HERE A SAMPLE OF THE PROVIDER


class BusinessProvider extends ChangeNotifier {
  BusinessModel businessModel = BusinessModel();

    void updateName(String nameChange) {
    businessModel.name = nameChange;
    notifyListeners();
  }


--
You received this message because you are subscribed to the Google Groups "Flutter Development (flutter-dev)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/flutter-dev/6798c59e-bcc1-455c-8572-a86d9735a949%40googlegroups.com.
Message has been deleted

Fer Buero Trebino

unread,
May 26, 2020, 5:48:19 AM5/26/20
to Flutter Development (flutter-dev)
I use quicktype.io to format my model class and it is not working with this nested model, until now it works perfect for me.

Fer Buero Trebino

unread,
May 26, 2020, 6:06:44 AM5/26/20
to Flutter Development (flutter-dev)
Suzuki, I attached the screen so you can pick up the line numbers, let me know if you need another file to check the problem.,

stacktrace.PNG






error.PNG




modelClass01.PNG




modelClass02.PNG






modelClass04.PNG



Thanks again!
:)
Fer

Suzuki Tomohiro

unread,
May 26, 2020, 7:52:01 AM5/26/20
to Fer Buero Trebino, Flutter Development (flutter-dev)
Your stacktrace somehow does not show line numbers. Can you figure out how to show the line numbers in the stacktrace?


<blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-style:solid;padding-left:1ex;border-left
Reply all
Reply to author
Forward
0 new messages