首页 > 解决方案 > 我如何将我的课程编码为 json 以将 http put 发送到 firebase

问题描述

我正在尝试对我的类进行编码以向 firebase 发送一个 put http,但是当我打印 User.toMap 时,我的函数显示了一个带有“'Address' 实例”的列表。

{id: -LVsaRJKo3vo6q9NWZn_, name: User 38197, email: null, address: [Instance of 'Address']}
class User {
  String id;
  String name;
  String email;
  List<Address> address = new List<Address>();

  User({this.id, this.name, this.email, this.address});

  User.fromMap(Map<String, dynamic> map) {
    this.id = map['id'];
    this.name = map['name'];
    this.email = map['email'];

    if (map['address'] == null) {
      this.address = new List<Address>();
    } else {
      this.address= (map['address'] as List).map((i) => Address.fromMap(i)).toList();
    }
  }

  Map<String, dynamic> toMap() {
    return {'id': id, 'name': name, 'email': email, 'address': address};
  }
}

===

class Address {
  String test;

  Address ({this.test});

  Address.fromMap(Map<String, dynamic> map) {
    this.test = map['test'];
  }

  Map<String, dynamic> toMap() {
    return {
      'test': test
  }
}

===

在类 ApiProvider

Future<User> updateUser(User userUpdate) async {
    String id = userUpdate.id;

    print(userUpdate.toMap()); // This prints that line

    final http.Response response = await http.put(
      baseUrl + '/user/$id.json',
      body: json.encode(userUpdate.toMap()), // Here happens the error
    );

    final Map<String, dynamic> userData = json.decode(response.body);
    User user = new User.fromMap(userData);   

    return user;
  }

===

最后的错误:

I/flutter (17495): {id: -LVsaRJKo3vo6q9NWZn_, name: User 38197, email: null, address: [Instance of 'Address']}
E/flutter (17495): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error:     Unhandled exception:
E/flutter (17495): Converting object to an encodable object failed: Instance of 'Address'
E/flutter (17495): #0      _JsonStringifier.writeObject (dart:convert/json.dart:703:7)
E/flutter (17495): #1      _JsonStringifier.writeList (dart:convert/json.dart:753:7)
E/flutter (17495): #2      _JsonStringifier.writeJsonValue (dart:convert/json.dart:735:7)
E/flutter (17495): #3      _JsonStringifier.writeObject (dart:convert/json.dart:693:9)
E/flutter (17495): #4      _JsonStringifier.writeMap (dart:convert/json.dart:786:7)
E/flutter (17495): #5      _JsonStringifier.writeJsonValue (dart:convert/json.dart:741:21)
E/flutter (17495): #6      _JsonStringifier.writeObject (dart:convert/json.dart:693:9)

标签: jsonflutter

解决方案


  Map<String, dynamic> toMap() {
    return {'id': id, 'name': name, 'email': email, 'address': address};
  }

需要改为

  Map<String, dynamic> toMap() {
    return {'id': id, 'name': name, 'email': email, 'address': address.map((a) => a.toMap()).toList()};
  }

推荐阅读