我试图在扑朔迷离中建立一个动态的TextField列表,但不了解如何处理它。
ListView.builder( shrinkWrap: true, itemCount: itemList.length, itemBuilder: (context, index) { if(itemList.length == null) { return _buildProgressIndicator(); } else { return singleItemList(index); } }) Widget singleItemList(int index) { if((itemList.length -1) < index) { return Container(child: null); } else { dynamic singleItem = itemList[index]; String counter = (index+1).toString(); return Container( decoration: BoxDecoration( color: Colors.white, ), child: Row( children:[ Expanded( flex: 1, child: Text(counter,style: orderBookItemListCounter(),) ), Expanded( flex: 3, child: TextField( controller: _addProductToCart(counter), decoration: InputDecoration( labelText: "Qty", ), ) ), ]) ); } }
Thanks :)
您有几种选择,具体取决于您如何构建应用程序或在哪里拥有中心状态。
我在这里为您提出一种更新本地地图变量的解决方案。或者,您可以将事件/流发送到商店所在的地方。
import 'package:flutter/material.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { List<Item> itemList = [ Item("ID1", "First product"), Item("ID2", "Second product"), ]; Map<String, int> quantities = {}; void takeNumber(String text, String itemId) { try { int number = int.parse(text); quantities[itemId] = number; print(quantities); } on FormatException {} } Widget singleItemList(int index) { Item item = itemList[index]; return Container( decoration: BoxDecoration( color: Colors.white, ), child: Row( children: [ Expanded(flex: 1, child: Text("${index + 1}")), Expanded( flex: 3, child: TextField( keyboardType: TextInputType.number, onChanged: (text) { takeNumber(text, item.id); }, decoration: InputDecoration( labelText: "Qty", ), ), ), ], ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Demo")), body: Center( child: ListView.builder( shrinkWrap: true, itemCount: itemList.length, itemBuilder: (context, index) { if (itemList.isEmpty) { return CircularProgressIndicator(); } else { return singleItemList(index); } }), ), ); } } class Item { final String id; final String name; Item(this.id, this.name); }