Flutter 方法';添加';在null上被调用,并尝试调用:add(字符串)

Flutter 方法';添加';在null上被调用,并尝试调用:add(字符串),flutter,Flutter,我试图将hospitalId字符串添加到列表字符串中。它不起作用,我不知道为什么。日志上写着 I/flutter (28204): The method 'add' was called on null. I/flutter (28204): Receiver: null I/flutter (28204): Tried calling: add("8a041434-0703-11eb-adc1-0242ac120002") 我的代码是: List<String&g

我试图将hospitalId字符串添加到列表字符串中。它不起作用,我不知道为什么。日志上写着

I/flutter (28204): The method 'add' was called on null.
I/flutter (28204): Receiver: null
I/flutter (28204): Tried calling: add("8a041434-0703-11eb-adc1-0242ac120002")
我的代码是:

 List<String>hospitalIds=List<String>();
 void _addLastSearch(String hospitalId,String hospitalName)
  {
   
    final lastSearching=SearchModel(hospitalId: hospitalId,hospitalName: hospitalName);
    setState(() {
                 recentSearch.add(lastSearching);
                 hospitalIds.add(hospitalId);
      });
    
      print("hospital Id");
      print("============================");
      print(hospitalIds);
      print("============================");
       savedData();
  
   
  }
ListhospitalIds=List();
void\u addLastSearch(字符串hospitalId,字符串hospitalName)
{
final lastsearch=SearchModel(hospitalId:hospitalId,hospitalName:hospitalName);
设置状态(){
添加(上次搜索);
hospitalId.add(hospitalId);
});
打印(“医院Id”);
打印(“====================================================”);
印刷品(医院);
打印(“====================================================”);
savedData();
}
我已尝试将列表更改为(无效):

ListhospitalIds=List();
ListHospitalID=[];

尝试如下初始化列表:


ListhospitalIds=[]

你在哪里声明了
recentSearch
?@ikerfah最近的搜索并不重要,问题发生在我添加“hospitalIds.add(hospitalId);”时,不知何故它无法添加它错误是说add在null上被调用,这意味着
recentSearch
hospitalIds
为null它100%肯定是hospitalIds先生,这回答了你的问题吗?
List<String>hospitalIds=List<String>();
   List<String>hospitalIds=[];