首页 > 解决方案 > 实例化嵌套对象 (Dart)

问题描述

在尝试将值分配给嵌套对象属性时,Dart treats the Nested Object(class OperandRange) as null.
默认值已分配给嵌套对象属性,但存在问题。

在下面的情况下,嵌套对象类OperandRange应分配最小值和最大值,但 dart 将其视为Null.

如何解决这个问题?

代码

import 'dart:io';

//Nested Object Class
class OperandRange{
  double _minValue = 0;
  double _maxValue = 10;

  OperandRange(this._minValue  , this._maxValue);

  double  get minValue => _minValue;

  double get maxValue => _maxValue;

 
  set minValue(double _val){

    _minValue = (_val)  ;
  }

 
  set maxValue(double _val){

    _maxValue = (_val)  ;
  }

}


class OperationData{

  List<OperandRange> operandList = [];//Nested Object
  List<String> operatorList = [] ;

  OperationData({this.operandList, this.operatorList});
}

void main(){
  int _operationCount = 2;
  OperationData _operation = OperationData();
  for(int _index = 0 ; _index < _operationCount ; _index++) {
    stdout.write(" Operation $_index - Name(string): ");
    _operation.operatorList[_index] = stdin.readLineSync();

    //Null Object
    stdout.write(" Operand $_index - Minimum Value (double) : ");
    _operation.operandList[_index]._minValue =
        double.parse(stdin.readLineSync());
    stdout.write(" Operand $_index - Maximum Value (double): ");
    _operation.operandList[_index]._maxValue =
        double.parse(stdin.readLineSync());

  }
}

错误

Operation 0 - Name(string): Add
Unhandled exception:
NoSuchMethodError: The method '[]=' was called on null.
Receiver: null
Tried calling: []=(0, "Add")
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1      main (1.dart:41:28)
#2      _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
#3      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)

Process finished with exit code 255

标签: dart

解决方案


这是正在发生的事情。

operandList您使用嵌套列表进行初始化。但这永远不会产生任何影响,因为您也在OperationData构造函数中对其进行了初始化。一旦您在构造函数参数中提及它,它将被设置为您传递给构造函数的值,或者如果您不将此参数传递给构造函数,则将其设置为 null。

出于您的目的,您可以完全删除构造函数,因为您从不向它传递任何东西。然后你的[]默认设置将成立。

否则,如果在某些情况下您需要使用自定义列表对其进行初始化,您可以这样做:

class OperationData{
  List<OperandRange> operandList;
  List<String> operatorList;

  OperationData({
    List<OperandRange> operandList,
    List<String>operatorList,
  }) :
    this.operandList = operandList ?? <OperandList>[],
    this.operatorList = operatorList ?? <String>[]
  ;
}

你的OperandRange课也是如此。0并且10永远不会使用默认值,因为构造函数需要显式值。顺便说一句,我根本看不到OperandRange创造。该列表保持为空。当您修复第一个错误时尝试越界访问索引时,您将捕获下一个错误。

如果可能的话,你也应该升级到 Dart 2.12。它引入了空安全性,会在编译时向您显示此错误。


推荐阅读