Flutter实现扫码未识别时自动填充表单标题输入框方案
Solution
Step 1: Modify the Form Function to Accept Scan Results
Update your _showFormadd function to take an optional scan result parameter, then pre-fill the title controller when creating a new entry:
void _showFormadd(int? id, {String? scanResult}) async { // Clear previous values to avoid leftover data _titleController.text = ''; _descriptionController.text = ''; _aantalController.text = ''; if (id != null) { // Load existing item details final existingJournal = _journals.firstWhere((element) => element['id'] == id); _titleController.text = existingJournal['title']; _descriptionController.text = existingJournal['description']; _aantalController.text = existingJournal['aantal']; } else if (scanResult != null) { // Pre-fill title with the scanned value for new entries _titleController.text = scanResult; } // Keep your existing showModalBottomSheet code unchanged here... }
Step 2: Add an "Add New Entry" Button to the Scan Result Section
In the UI where you display the unrecognized scan result, add a button that triggers the form with the scanned value preloaded:
Column( children: [ Text( 'Scan result : $_scanBarcode\n', textAlign: TextAlign.center, style: const TextStyle(fontSize: 20, height: 30), ), ElevatedButton( onPressed: () { // Open form to create new entry with scan result in title _showFormadd(null, scanResult: _scanBarcode); }, child: const Text('Add New Entry'), ), ], )
Step 3: Polish the Title TextField (Optional)
Add a hint to the title TextField for better usability:
TextField( controller: _titleController, decoration: const InputDecoration(hintText: 'Title'), )
Key Details
- Controllers are reset at the start of
_showFormaddto ensure no leftover data from previous uses. - The
scanResultparameter is optional, so the function still works for regular new entries (without scanning). - When creating a new entry (
id == null) and a scan result is provided, the title field automatically populates with the scanned value.
内容的提问来源于stack exchange,提问作者Renzo
相关产品推荐
相关产品推荐

