flutter - 学习 flutter

标签 flutter dart

我是塞内加尔的阿里。我今年60岁(也许这是我真正的问题-笑脸!!!)。
我正在学习Flutter和Dart。今天,我想使用给定数据模型的列表(它的名称是Mortalite,请参见下面的代码)。
我尝试使用dartpad。我很伤心,因为我不明白为什么以下代码片段无法运行:
//https://www.dartpad.dev/

void main(){
  print('Beginning');
  
  List<Mortalite>pertes;
  
  var causes = ['Bla0', 'Bla1', 'Bla2', 'Bla3'];
  var lstDate = ['21/09/2020', '22/09/2020', '23/09/2020', '24/09/2020'];
  var perteInst = [2, 4, 3, 1];
  var total=0;

  for (int i = 0; i < 4; i++) {
    total += perteInst[i];
    print(i);                           // prints only '0'
    
    pertes[i] = new Mortalite(
      causesPerte: causes[i],
      datePerte: lstDate[i], 
      perteInstant:perteInst[i],
      totalPertes: total);
      };
   print(pertes.length);                // nothing printed
   print('Why?');                       // nothing printed
 }

class Mortalite {
  String datePerte;
  String causesPerte;
  int perteInstant; // pertes du jour
  int totalPertes; // Total des pertes.
  Mortalite(
    {this.datePerte, 
     this.causesPerte, 
     this.perteInstant, 
     this.totalPertes}
  );
}
非常感谢您的帮助。
科特

最佳答案

上面的代码不起作用的原因是因为您已初始化List pertes,并且要传递给pertes的元素。当您尝试将pertes的索引传递给0时,它找不到它并抛出范围错误,因为pertes还没有索引0。请查看下面的修复程序,如果您需要任何帮助,请告诉我。

void main(){
  print('Beginning');
  
  List<Mortalite>pertes=[];
  
  var causes = ['Bla0', 'Bla1', 'Bla2', 'Bla3'];
  var lstDate = ['21/09/2020', '22/09/2020', '23/09/2020', '24/09/2020'];
  var perteInst = [2, 4, 3, 1];
  var total=0;

  for (int i = 0; i < causes.length; i++) {
    total += perteInst[i];                           // prints only '0'
    
    pertes.add (new Mortalite(
      causesPerte: causes[i],
      datePerte: lstDate[i], 
      perteInstant:perteInst[i],
      totalPertes: total));
                };
   print(pertes.length);                // nothing printed                      // nothing printed
 }

class Mortalite {
  String datePerte;
  String causesPerte;
  int perteInstant; // pertes du jour
  int totalPertes; // Total des pertes.
  Mortalite(
    {this.datePerte, 
     this.causesPerte, 
     this.perteInstant, 
     this.totalPertes}
  );
}

关于flutter - 学习 flutter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64656318/

相关文章:

flutter - 如何在flutter中的DecorationImage()内编写if语句

forms - Flutter - 使用子 map 属性发送表单帖子

flutter - 如何根据 Flutter 中具有动态大小的小部件的大小设置角半径

flutter - 仅基于Type实例在Dart中进行类型继承检查

dart - 当点击后退按钮导航到我访问的每个页面时

dart - 断言失败 : 'userRepository != null' : is not true

flutter - 在flutter中将内存图像(如Uint8list)保存为图像文件

firebase - Flutter - Mockito Firestore...get() - 在 null 上调用方法 'document'

firebase - StreamBuilder返回null

dom - 如何使用 Dart 将 SVG 元素保存到静态文件?