我想以这种方式从 this JSON 读取数据(请阅读代码注释):
class Profile extends StatefulWidget {
final id;
Profile({Key? key, @required this.id}) : super(key: key);
@override
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
var data;
@override
void initState() {
super.initState();
void getData() async {
Response response = await get(
Uri.parse('https://en.gravatar.com/' + widget.id + '.json'));
this.data = json.decode(utf8.decode(response.bodyBytes));
// READ PLEASE >>> Data successfully is loaded from server & if you
// print this.data it will show full data in console <<< READ PLEASE
}
getData();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Profile | MWX Gravatar Viewer',
home: Scaffold(
appBar: AppBar(
title: Text('Profile | MGV'),
),
body: Center(
child: Column(
children: [
Text(this.data['entry'][0]['name']['familyName']), // Where raises error
],
),
),
),
);
}
}
我在渲染页面时收到此错误:
The following NoSuchMethodError was thrown building Profile(dirty, state: _ProfileState#35267):
The method '[]' was called on null.
Receiver: null
Tried calling: []("entry")
注意: 热重载错误消失后,我可以在屏幕上看到我需要的数据,但是每次当我想加载页面时,都会显示此错误,尽管我可以看到我的内容预期,热重载后
答案 0 :(得分:1)
这是因为您正在调用网络请求,同时您正在使用默认为空的数据,因此您可以使用 FutureBuilder()
或通过 null check
处理错误
答案 1 :(得分:1)
您的身体可能正在运行,而不是在 getData()
等待您的 initState
。在使用之前尝试检查它是否为空:
body: Center(
child: Column(
children: [
Text(this.data != null ? this.data['entry'][0]['name']['familyName'] : 'no data'), // Where raises error
],
),
),
或者使用 FutureBuilder
。