如何在Flutter中实现基于指定字符串的输入验证条件判断?
Hey there! Since you're new to Flutter, I’ve put together a simple, fully working implementation that fits your needs perfectly. Let’s dive right into it—this code will work seamlessly in your Android Studio 3.5.2 setup with updated environments.
Complete Flutter Implementation
Here’s the full code for your screen. I’ve added comments to explain each part so you can follow along easily:
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Country Validation', theme: ThemeData( primarySwatch: Colors.blue, ), home: const ValidationScreen(), ); } } class ValidationScreen extends StatefulWidget { const ValidationScreen({super.key}); @override State<ValidationScreen> createState() => _ValidationScreenState(); } class _ValidationScreenState extends State<ValidationScreen> { // Controller to get input from the text field final TextEditingController _inputController = TextEditingController(); // Variable to store the message we'll display String _displayMessage = ''; // List of valid countries/regions we need to check against final List<String> _validLocations = ['Philippines', 'Dubai', 'Japan']; // Function to validate input and update the display message void _checkInput() { String userInput = _inputController.text.trim(); setState(() { if (_validLocations.contains(userInput)) { _displayMessage = 'Welcome from "$userInput"'; } else { _displayMessage = 'Does not match data'; } }); } @override void dispose() { // Always dispose the controller to avoid memory leaks _inputController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Input Validation'), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ // Input TextField TextField( controller: _inputController, decoration: const InputDecoration( labelText: 'Enter a location', border: OutlineInputBorder(), ), ), const SizedBox(height: 20), // Submit Button ElevatedButton( onPressed: _checkInput, child: const Text('Submit'), ), const SizedBox(height: 20), // Display Message Text( _displayMessage, style: TextStyle( fontSize: 18, color: _displayMessage.startsWith('Welcome') ? Colors.green : Colors.red, ), ), ], ), ), ); } }
Key Details for New Flutter Devs:
- StatefulWidget: We use this because we need to update the UI (the display message) when the user clicks the button—stateless widgets can’t change their state after being built.
- TextEditingController: This tool lets us easily access the text the user types. Remember to call
dispose()on it when the widget is destroyed to prevent memory leaks! - Validation Logic: The
_checkInput()method first trims extra spaces from the input, then checks if it’s in our list of valid locations. UsingsetState()tells Flutter to rebuild the UI with the new message. - Visual Feedback: I added color coding to the message—green for success, red for errors—to make the result clearer at a glance.
Just copy this code into your project’s main.dart file and run it. It should behave exactly as you described!
内容的提问来源于stack exchange,提问作者Aia's Blog
相关产品推荐
相关产品推荐

