英文:
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<List<StyleModel>> listofSubstyles=[[]];
final List<StyleModel> _subStyle =<StyleModel> [];
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<List<StyleModel>> listofSubstyles = [[]];
to
List<List<StyleModel>> listofSubstyles = [];
Problem:
During initialization List<List<StyleModel>> 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<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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论