【问题标题】:How to properly initialize a list如何正确初始化列表
【发布时间】:2021-09-07 03:33:58
【问题描述】:

所以,我正在尝试根据 item.lenght 将 int 列表初始化为 0,但我不断收到错误 RangeError (index): Invalid value: Valid value range is empty: 0强>

import 'package:flutter/material.dart';

class DisplayAttributes extends StatefulWidget {
  const DisplayAttributes({
    Key key,
    //@required this.attribute,
    this.data,
    this.variableProducts,
    Function onChanged,
  }) : super(key: key);

  //final Attributes attribute;
  final Product data;
  final List<ProductVariation> variableProducts;

  @override
  _DisplayAttributesState createState() => _DisplayAttributesState();
}

class _DisplayAttributesState extends State<DisplayAttributes> {
  int activeOption = 0; //to replace with
  List activeOptions = [];

  @override
  void initState() {
    for (int i = 0; i >= this.widget.data.attributes.length; i++) {
      activeOptions[i] = 0;
    }
    print(this.widget.data.attributes.length); // returns 7
    print(activeOptions[0]); // returns RangeError (index): Invalid value: Valid value range is empty: 0
    super.initState();
  }

【问题讨论】:

  • 使用List.filled构造函数
  • 谢谢,List.filled 正在工作.. 但是为什么我写的东西不起作用??
  • 因为你的列表是空的所以你甚至不能做activeOptions[0] = 0;

标签: flutter


【解决方案1】:

您应该使用.filled 工厂构造函数

  @override
  void initState() {
List.filled(this.widget.data.attributes.length, 0,growable: true);
...

【讨论】:

    【解决方案2】:

    你说过 List activeOptions = [];,表示activeOptions是一个空列表。

    那么您正在尝试为其增加价值activeOptions[i] = 0;。这意味着i index 的值是0。但实际上,List activeOptions 是空的。所以,这个说法是错误的。

    正确的方法是activeOptions.add(0);。这会将0 添加到列表中。

    如果你能分享完整的代码或者这个函数的使用,也许我可以给你一些建议。

    【讨论】:

      猜你喜欢
      • 2022-01-01
      • 2010-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      • 2016-12-22
      • 1970-01-01
      相关资源
      最近更新 更多