1

i have no experience with extended classes so don't be shocked... that's what I got:

the 'basic class' I want to extend in my models to avoid repeat fromJson/toJson every 2 lines

    import 'dart:convert';

class BaseModel {
  Map<String, dynamic> json2Map(String json) => jsonDecode(json);
  String map2Json(Map<String, dynamic> map) => jsonEncode(map);

  json2List(String jsonList) {
    List<Map<String, dynamic>> _list = [];
    jsonDecode(jsonList).forEach((_json) => _list.add(jsonDecode(_json)));
    return _list;
  }

  mapList2Json(List<Map<String,dynamic>> list) {
    List<String> jsonList= [];
    list.forEach((_map) => jsonList.add(map2Json(_map)));
    return jsonEncode(jsonList);
  }
}

and here is one of the class that extends this:

    import 'package:bloc_hub/models/base_model.dart';

class Info extends BaseModel {
  final String name;
  final String company;
  Info({this.name,this.company});

  factory Info.fromMap(Map<String, dynamic> json) => new Info(
        name: json['name'],
        company: json['company'],
    );

  Map<String, dynamic> toMap()  {
    var map = new Map<String, dynamic>();
    map['name'] = name;
    map['company'] = company;
      return map;
  }
}

(I'm in a streambuilder and client.info is a json) then... when I try to call 'json2map' which is from the extended class...

Info info = Info.fromMap(json2Map(client.info));

i get this:

[dart] The method 'json2Map' isn't defined for the class 'ListPage'. [undefined_method]

what did I get wrong? if I wasn't clear don't refrain to ask me anything

thank you for your help

[edit: bonus question how a mixin is different from what I'm doing?]

Francesco Iapicca
  • 2,618
  • 5
  • 40
  • 85

1 Answers1

1

json2Map is an instance method of BaseModel, so in order to call it you must use an instance of BaseModel or a class that extends it (like Info), like:

var b = new BaseModel();
b.json2Map(something);

The error message says you're calling it from ListPage, so the method is not found.

Alternatively, you could make the methods static and call it like BaseModel.json2Map(...) (without an instance).

There are some good explanations about mixins here (with Python examples, but the concepts are the same for Dart). I guess in your example it would make more sense to have a mixin with JSON related functions, since you could use them in other kind of objects.

Vinicius Braz Pinto
  • 8,209
  • 3
  • 42
  • 60