我想知道如何使用Cloud Functions Plugin for Flutter发送或发布地图列表。
我有一些这样的地图:
var customer1 = {'name':'tom','lastname':'smith'};
var customer2 = {'name':'bob','lastname':'lee'};
var customer3 = {'name':'george','lastname':'collins'};
这些地图后来成为一个列表:
var _customerList = [customer1, customer2, customer3];
我正在尝试将此列表作为参数发送或发布到云函数中,以便进行如下颤振:
var _data = {
'customerList': _customerList,
};
final HttpsCallable callable = CloudFunctions.instance
.getHttpsCallable(functionName: 'createCustomer')
..timeout = const Duration(seconds: 30);
final HttpsCallableResult result = await callable.call(_data);
但是,我得到这个错误:
I/flutter (11486): Invalid argument: Instance of ...
如果我尝试发布一个简单的字符串,一切都会正常工作。不过,我似乎没有正确地张贴地图列表。
我正在使用此版本的插件:
dependencies:
cloud_functions: ^0.3.0+1
谢谢你的帮助。
最佳答案
将复杂数据结构序列化/反序列化为JSON对象的简单方法是使用包marshalling
原型(使用“yaml”格式)
json_对象.yaml
Customer:
name: String
lastname: String
CustomerList:
customerList: List<Customer>
自动生成代码(使用实用程序“yaml2podo”)。
pub global run marshalling:yaml2podo json_objects.yaml
json_objects.dart
// Generated by tool.
import 'package:marshalling/json_serializer.dart';
final json = JsonSerializer()
..addType(() => Customer())
..addType(() => CustomerList())
..addIterableType<List<Customer>, Customer>(() => <Customer>[])
..addAccessor('customerList', (o) => o.customerList, (o, v) => o.customerList = v)
..addAccessor('lastname', (o) => o.lastname, (o, v) => o.lastname = v)
..addAccessor('name', (o) => o.name, (o, v) => o.name = v)
..addProperty<Customer, String>('name')
..addProperty<Customer, String>('lastname')
..addProperty<CustomerList, List<Customer>>('customerList');
class Customer {
String name;
String lastname;
Customer();
factory Customer.fromJson(Map map) {
return json.unmarshal<Customer>(map);
}
Map<String, dynamic> toJson() {
return json.marshal(this) as Map<String, dynamic>;
}
}
class CustomerList {
List<Customer> customerList;
CustomerList();
factory CustomerList.fromJson(Map map) {
return json.unmarshal<CustomerList>(map);
}
Map<String, dynamic> toJson() {
return json.marshal(this) as Map<String, dynamic>;
}
}
使用生成的代码(自动序列化/反序列化对象)
import 'json_objects.dart';
void main() {
var customers = <Customer>[];
var customer = Customer()
..name = 'tom'
..lastname = 'smith';
customers.add(customer);
customer = Customer()
..name = 'bob'
..lastname = 'lee';
customers.add(customer);
customer = Customer()
..name = 'george'
..lastname = 'lee';
customers.add(customer);
var customerList = CustomerList();
customerList.customerList = customers;
var data = customerList.toJson();
// final HttpsCallableResult result = await callable.call(data);
print(data);
}
结果:
{customerList: [{name: tom, lastname: smith}, {name: bob, lastname: lee}, {name: george, lastname: lee}]}
关于firebase - 如何将列表作为参数发送到Flutter中的Firebase函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56303963/