将值分配给Flutter中的二维数组

huangapple go评论69阅读模式
英文:

Assign the value to a two-dimensional array in Flutter

问题

考虑以下代码:

List<List<StyleModel>> listofSubstyles=[[]];
final List<StyleModel> _subStyle =<StyleModel> [];
listofSubstyles.add(_subStyle);


我的数组是动态的,我想像这样添加数据:

    listofSubstyles[index].add(_subStyle);

但是显示错误:值超出范围。

向二维数组中输入数据会显示错误。
英文:

Consider:

List&lt;List&lt;StyleModel&gt;&gt; listofSubstyles=[[]];
final List&lt;StyleModel&gt; _subStyle =&lt;StyleModel&gt; [];
listofSubstyles.add(_subStyle);

My array is dynamic and I want to add data like this:

listofSubstyles[index].add(_subStyle);

But it's showing an error: value is out of range.

Entering data into a two-dimensional array shows errors.

答案1

得分: 0

Quick Solution:

Change

List<List<StyleModel>> listofSubstyles = [[]];

to

List<List<StyleModel>> listofSubstyles = [];

Problem:

During initialization List<List<StyleModel>> listofSubstyles=[[]] this initializes the listofSubstyles with a single empty list, meaning using listofSubstyles[index] to retrieve an element at a particular index will only be successful if the index is equal to 0, else an error will be thrown.

Updated code:

List<List<StyleModel>> listofSubstyles = [];
final List<StyleModel> _subStyle = <StyleModel> [];
listofSubstyles.add(_subStyle);

// add a new empty sublist
listofSubstyles.add([]);

// add data to the sublist at index 1
listofSubstyles[1].add(_subStyle);
英文:

Quick Solution:

Change

List&lt;List&lt;StyleModel&gt;&gt; listofSubstyles = [[]];

to

List&lt;List&lt;StyleModel&gt;&gt; listofSubstyles = [];

Problem:

During initialization List&lt;List&lt;StyleModel&gt;&gt; listofSubstyles=[[]] this initialises the listofSubstyles with a single empty list, meaning using listofSubstyles[index] to retrieve an element at a particular index will only be successful if index is equal to 0 else error will be thrown.

Updated code:

List&lt;List&lt;StyleModel&gt;&gt; listofSubstyles = [];
final List&lt;StyleModel&gt; _subStyle = &lt;StyleModel&gt; [];
listofSubstyles.add(_subStyle);

// add a new empty sublist
listofSubstyles.add([]);

// add data to the sublist at index 1
listofSubstyles[1].add(_subStyle);

huangapple
  • 本文由 发表于 2023年3月7日 04:35:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655582.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定