android - NoSuchMethodError:在 null 上调用了 getter 'avatar'
问题描述
看过类似的问题,看不到任何常见的错误。一旦工厂似乎可以毫无问题地创建对象。但是,调用任何方法都会生成 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,
),
);
}
解决方案
代码没有错误,将帖子 ID 而不是用户 ID 返回给函数,因此出现空错误。
推荐阅读
- flutter - 如何在颤动中创建一个始终粘在页面底部的按钮?
- javascript - 几个图在flot中具有相同的图例
- ais - 如何根据 AIS 140 标准计算校验和
- python - 如何使用 igraph 将 numpy 数组转换为图形?
- rabbitmq - 业务数据在 RabbitMQ 消息中的位置
- audio - ffmpeg 默认音频编解码器,而不是使用 acodec 选项指定它
- css - Shiny App中的随机加载页面图像
- c++ - 析构函数如何在一个简单的程序中工作?
- laravel - 自定义中间件在控制器中不起作用(Laravel)
- android - 使用 MediaBrowserService 构建 Podcast 应用程序