为什么在比较类时关键字“ is”不能按预期运行?

时间:2019-08-14 11:28:32

标签: dart

我在dart应用程序中使用redux模式。在化简器中,具有"is"关键字以找出正在传递哪个动作(以类的形式)的if语句根本不起作用。

DictionaryState dictionaryReducer(DictionaryState state, dynamic action){

  if(action is RequestingDictionaryEntryAction){
    // This if statement should be executed but it is not.
    return _requestingDictionaryEntry(state);
  }

  if(action is ReceivedDictionaryEntryAction){
    return _receivedDictionaryEntry(state, action);
  }

  return state;
}

在调用dictionaryReducer时,我正在传递一个名为RequestingDictionaryEntryAction的操作,但该操作未被识别为RequestingDictionaryEntryAction,而是代码继续执行并且该函数未按预期返回

2 个答案:

答案 0 :(得分:1)

就在我头顶上,所以不要过分相信,但是您的问题可能出在参数的“动态”类型上,导致is运算符在编译时失败。我认为可以使用以下方法解决此问题:

DictionaryState dictionaryReducer(DictionaryState state, dynamic action){

  if(action.runtimeType == RequestingDictionaryEntryAction){
    return _requestingDictionaryEntry(state);
  }

  if(action.runtimeType == ReceivedDictionaryEntryAction){
    return _receivedDictionaryEntry(state, action);
  }

  return state;
}

答案 1 :(得分:0)

问题出在我作为action传递的参数中。我没有正确实例化该类。我正在传递类声明本身,而不是它的瞬间。

final action = RequestingDictionaryEntryAction代替

final action = RequestingDictionaryEntryAction();

:D:D