flutter - 我该如何解决它“必须向文本小部件提供非空字符串”
问题描述
当我尝试编写位置名称时,它会显示此错误。这是我用来预测位置名称的小部件的代码:
class PredictionTile extends StatelessWidget
{
final PlacePredictions placePredictions;
PredictionTile({Key key, this.placePredictions}) : super(key: key);
@override
Widget build(BuildContext context)
{
return Container(
child: Column(
children: [
SizedBox(width: 10.0,),
Row(
children: [
Icon(Icons.add_location,color: Colors.redAccent,),
SizedBox(width: 10.0,),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 10.0,),
Text(placePredictions.main_text,overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 16.0),), //show suggestion
SizedBox(height: 3.0,),
Text(placePredictions.secondary_text,overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12.0,color: Colors.grey),),
SizedBox(height: 10.0,),
],
),
),
],
),
SizedBox(width: 10.0,),
],
),
);
}
}
解决方案
有多种方法可以防止错误发生。
您可以在构造函数中标记
PlacePredictions
类的两个属性。required
PlacePredictions
PlacePredictions({required this.main_text, required this.secondary_text});
这样,每当您忘记传递这两个属性时,您的 IDE 都会向您发出警告。
PlacePredictions
否则,如果您在创建实例时不能或不想传入值,则可以为它们设置默认值。最后,您始终可以在小部件本身中处理此逻辑。
Text(placePredictions.main_text ?? 'oops no text here');
推荐阅读
- c# - C#用户控件智能标签
- javascript - 在 mousedown 事件中添加的 Mousemove 事件在鼠标不移动时不断触发
- xml - 为每个 xml 元素生成一行
- flowtype - Flow中默认参数的问题
- reactjs - 如何使用 Rollup 使 React 组件导入提取的 scss 模块文件?
- javascript - React 钩子将映射的复选框值添加到数组或删除它
- python - 如何让代码在速度方面更有效率
- arrays - 将一行 `top`、`htop` 或 `intel_gpu_top` 输出保存到 Bash 数组中
- c - 读取方向存储在指针中
- python - 使用 Python 获取 XML 值和标签