问题描述
看过类似的问题,看不到任何常见的错误。一旦工厂似乎可以毫无问题地创建对象。但是,调用任何方法都会生成NoSuchMethodError。调试了好几天,没了主意。可以使用具有一般布局的数据模型的类似代码,而不会出现任何问题。
这是数据模型的代码
class Performer {
String avatar,header,name,username;
int id,subscribePrice;
bool isRealPerformer,isPerformer,hasStories,hasStream,isPaywallRestriction;
Performer(
{this.avatar,this.header,this.name,this.username,this.id,this.subscribePrice,this.isRealPerformer,this.isPerformer,this.hasStories,this.hasStream,this.isPaywallRestriction});
factory Performer.fromJson(Map<String,dynamic> performer) {
return Performer(
avatar: performer["avatar"],header: performer["header"],name: performer["name"],username: performer["username"],id: performer["id"],subscribePrice: performer["subscribePrice"],isRealPerformer: performer["isRealPerformer"],isPerformer: performer["isPerformer"],hasStories: performer["hasStories"],hasStream: performer["hasStream"],isPaywallRestriction: performer["isPaywallRestriction"]);
}
}
这是填充模型的代码
Future<List<Performer>> getSubscriptions() async {
List<Performer> performers = [];
String url = "some API url";
String res = await _callServer(url);
if (res.isNotEmpty) {
List<dynamic> payload = json.decode(res);
payload.forEach((element) {
performers.add(new Performer.fromJson(element));
});
return performers;
} else return performers;
}
Future<Performer> getPerformer(int performerID) async {
List<Performer> subs = await getSubscriptions();
Performer performer;
int prefIndex;
for (int x = 0; x < subs.length; x++) {
if (subs[x].id == performerID){
performer = subs[x];
break;
}
}
if (performer.avatar != null) {
print("found ${performer.username}");
return performer;
} else return null;
}
这是基于模型生成UI元素的代码
class ProfilePic extends StatefulWidget {
final int id;
ProfilePic({Key key,@required this.id}) : super();
@override
State<StatefulWidget> createState() => _profilePicState();
}
class _profilePicState extends State<ProfilePic> {
Performer performer;
@override
void initState() {
// TODO: implement initState
super.initState();
Backend().getPerformer(widget.id).then((value) {
performer = value;
setState(() {});
});
}
@override
Widget build(BuildContext context) {
print("profile for: ${widget.id}");
return Container(
child: performer == null ? Container() : CircleAvatar(
radius: 30.0,backgroundImage:
NetworkImage(performer.avatar),backgroundColor: Colors.transparent,),);
}
解决方法
在您的getSubscriptions
中,尝试
payload.forEach((element) {
performers.add(new Performer.fromJson(Map.from(element)));
});
,
代码没什么问题,是将帖子ID而非用户ID返回给函数,因此返回空错误。