App/Flutter

[ FLUTTER ] +연산자오버로딩을 이용하여 null값 처리하기

거북 2023. 7. 17. 23:33

 

extension OptionalInfixAddition<T extends num> on T? {
  T? operator +(T? other) {
    return (this??0) + (other??0) as T;
  }
}

void main() {
  final int? n1 = null;
  final int? n2 = 3;
  print('res: ${n1 + n2}');
}

결과 : res: 3