首页 > 解决方案 > 我该如何解决它“必须向文本小部件提供非空字符串”

问题描述

当我尝试编写位置名称时,它会显示此错误。这是我用来预测位置名称的小部件的代码:

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,),
        ],
      ),
    );
  }
}

在此处输入图像描述

标签: flutterdarterror-handlinguber-api

解决方案


有多种方法可以防止错误发生。

  1. 您可以在构造函数中标记PlacePredictions类的两个属性。requiredPlacePredictions

    PlacePredictions({required this.main_text, required this.secondary_text});
    

这样,每当您忘记传递这两个属性时,您的 IDE 都会向您发出警告。

  1. PlacePredictions否则,如果您在创建实例时不能或不想传入值,则可以为它们设置默认值。

  2. 最后,您始终可以在小部件本身中处理此逻辑

    Text(placePredictions.main_text ?? 'oops no text here');
    

推荐阅读