在await中为对象字段分配新值会阻止进一步的指示

问题描述 投票:0回答:1

我坚持这一点,我不知道为什么最后一个打印不执行过去的对象值初始化。

await _client
      .get(Uri.parse(_url), headers: {"location": "Mars"})
      .then((result) => result.body)
      .then(json.decode)
      .then((json) => json.forEach((person) {
        print(person); // this gets executed and printed over and over
        Person newPerson;
        print('hehe lolz'); // this gets executed too
        newPerson.status = person['status'];
        print('hello'); // this never gets executed...

Person类只是一个包含所有String字段和构造函数的模型。

有什么可能阻止最后一次打印的执行?

asynchronous dart flutter
1个回答
1
投票

这是因为newPerson为null,并且当您尝试调用newPerson.status时 - 出现NullPointer异常并且下面的所有代码都不会执行。只需:

Person newPerson = Person();
© www.soinside.com 2019 - 2024. All rights reserved.