如何在Flutter循环中创建指定数量的相同输入元素?
Hey there! I totally get how frustrating it is to hunt for solutions for hours without luck—let’s fix this together. Here’s a straightforward, actionable way to create dynamic input fields based on a numeric value in Flutter, and collect their input into an array.
Step 1: Set Up State Variables
First, we’ll need two key state variables: one to track the number of input fields you want, and another array to store the values from each field.
class DynamicInputScreen extends StatefulWidget { const DynamicInputScreen({super.key}); @override State<DynamicInputScreen> createState() => _DynamicInputScreenState(); } class _DynamicInputScreenState extends State<DynamicInputScreen> { // Controls how many input fields to generate (can be updated by user input) int numberOfFields = 0; // Array to store values from each input field List<String> inputValues = []; @override void initState() { super.initState(); // Initialize the array with empty strings if you start with a default number // inputValues = List.generate(3, (index) => ''); } }
Step 2: Build Dynamic Input Fields
Use a ListView.builder (or Column if you know the number won’t exceed screen height) to loop and generate input fields. Each field will be tied to a specific index in the array, so we can update values in real-time.
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Dynamic Inputs')), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( children: [ // Let the user input the number of fields they need TextField( keyboardType: TextInputType.number, decoration: const InputDecoration( labelText: 'Enter number of input fields', border: OutlineInputBorder(), ), onChanged: (value) { setState(() { // Update the number of fields (fallback to 0 if input is invalid) numberOfFields = int.tryParse(value) ?? 0; // Reset the array to match the new number of fields inputValues = List.generate(numberOfFields, (index) => ''); }); }, ), const SizedBox(height: 24), // Generate the dynamic input fields Expanded( child: ListView.builder( itemCount: numberOfFields, itemBuilder: (context, index) { return Padding( padding: const EdgeInsets.only(bottom: 12.0), child: TextFormField( initialValue: inputValues[index], decoration: InputDecoration( labelText: 'Field ${index + 1}', border: const OutlineInputBorder(), ), onChanged: (value) { // Update the array with the latest input value setState(() { inputValues[index] = value; }); }, ), ); }, ), ), // Button to verify collected values ElevatedButton( onPressed: () { // Use the inputValues array however you need! print('Collected input values: $inputValues'); // Example: Pass to an API, save to local storage, etc. }, child: const Text('View Collected Values'), ), ], ), ), ); } }
Step 3: Key Details to Note
- Array Initialization:
List.generate(numberOfFields, (index) => '')creates an array with empty strings matching the number of fields, so each input has a placeholder to update. - Real-Time Updates: The
onChangedcallback for eachTextFormFieldupdates the corresponding index ininputValues, ensuring the array always reflects the latest user input. - Dynamic Adjustments: If the user changes the number of fields, the array resets to match the new count—no leftover values from previous configurations.
内容的提问来源于stack exchange,提问作者Dayane Cordeiro
相关产品推荐
相关产品推荐

