flutter - Flutter - 为列表中的每个项目动态创建多个变量
问题描述
您好,我有一个简单的表格,基本上它将显示文章名称及其下方的所有服务,并且在同一行中将有 + 和 - 按钮将增加变量,但这里的问题是我不确切知道将有多少服务,因为服务将从应用程序的其他部分创建和链接,但是我可以使用 ListName.length 获取列表的长度
这是一个示例代码
int quantity = 0;
Column(
children: <Widget>[
articleName(article),
Column(
children: List.generate(price.length, (index) =>
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
padding: EdgeInsets.all(10),
child: Text(
translator.currentLanguage == 'ar' ?
'${price[index].serviceNameAr}'
:'${price[index].serviceNameEn}',
style: TextStyle(
fontSize: responsivenessController.font,
),
),
),
Text('${price[index].price}' ,
style: TextStyle(
fontSize: responsivenessController.bodyFont,
),
),
FloatingActionButton(
onPressed: (){
setState(() {
quantity = quantity + 1;
});
},
child: Icon(Icons.add, color: Colors.black,),
backgroundColor: Colors.white,
),
Text('$quantity',
style: TextStyle(fontSize: responsivenessController.font)),
FloatingActionButton(
onPressed: (){
setState(() {
quantity = quantity - 1;
});
},
child: Icon(Icons.remove , color: Colors.black,),
backgroundColor: Colors.white,
),
],
)
),
)
如您所见,如果您单击第三个服务上的添加按钮,例如,所有其他服务将具有相同的数量,因为它们共享相同的变量。
我想要的是当用户提交我想要的表单时
- 文章 id -> 存在于以前的代码中
- 服务 ID -> 存在
- 数量 -> 导致问题的那个
- 价格 -> 取决于数量
请与我分享你的想法,如果你遇到这样的问题你会怎么做
解决方案
您需要一份清单来保存您的数量。列表类似于其他编程语言中的数组。
尝试这样的事情:
List<int> quantities = [];
// initializing the list with the lenth provided
for(int i = 0; i<price.length; i++){
quantities.add(0);
}
并在您的 setState 中以这种方式使用列表:
quantities[index] = quantities[index] + 1 (or quantities[index]++;)
quantities[index] = quantities[index] - 1 (or quantities[index]--;)
推荐阅读
- c# - 有什么方法可以获取所有打开的应用程序的列表,然后跳转到那个窗口
- python - 如何从 python oop 中的另一个类访问对象?
- php - 未找到 Amazon S3 PHP SDK MultipartUploader 类
- angular - NPM Install 说“更新了 3 个包”,但没有说是哪些?
- c# - 当我尝试在 Xamarin Forms 上上传图像时,继续收到相同的错误
- google-data-studio - 在 Data Studio 的条形图中调整条形之间的间隙
- html - 如何在图像上使用 resize 属性?
- html - 如何避免页脚中没有线条的表格打印?
- javascript - 从对象与对象反应表
- python - UnboundLocalError:分配前引用了局部变量“file1”,请帮助修复