首页 > 解决方案 > Text() 出错 - 必须向 Text 小部件提供非空字符串

问题描述

我正在使用此存储库中的已完成项目(https://github.com/londonappbrewery/destini-challenge-completed

我在 Text() 小部件和后续调用中遇到错误。

storyBrain.getStory();
storyBrain.getChoice1();
storyBrain.getChoice2();

错误:

A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 285 pos 10: 'data != null'

在此处输入图像描述

解决方法- 我尝试使用将其转换为字符串,.toString()但仍然出现相同的错误。

颤振医生——

E:\Temp\flutter\destini-challenge-starting>flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
> Flutter (Channel stable, v1.12.13+hotfix.9, on Microsoft Windows [Version 10.0.18363.778], locale en-IN)

> Android toolchain - develop for Android devices (Android SDK version 29.0.2)
> Android Studio (version 3.6)
> VS Code, 64-bit edition (version 1.44.2)
> Connected device (1 available)

• No issues found!

标签: flutterdart

解决方案


这是因为你的对象还没有被初始化,为了解决这个问题,我们需要更多的代码,但是为了避免??像这样使用 null 异常,它会检查它之前的内容是否为 null 然后它会显示 after 的值??

storyBrain.getStory() ?? 'default value';
storyBrain.getChoice1() ?? 'default value';
storyBrain.getChoice2() ?? 'default value';


推荐阅读