2021年7月25日 星期日

[又重學flutter]Form / GlobalKey / FormState / TextFormField / RegExp (表單驗證)

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: HomePage(),
  ));
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  String result = '';
  
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: Container(
              padding: EdgeInsets.all(10.0),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    TextFormField(
                      validator: (String? value) {
                        if (!isWordAndDigit(value!)) {
                          return '請輸入英文或數字';
                        }
                        return null;
                      },
                    ),
                    GestureDetector(
                      onTap: () {
                        print(_formKey.currentState!.validate());
                        if (_formKey.currentState!.validate()) {
                          setState(() {
                            result = '驗證成功';
                          });
                        }
                      },
                      child: Container(
                        margin: EdgeInsets.symmetric(vertical: 10.0),
                        padding: EdgeInsets.all(10.0),
                        child: Text('按鈕'),
                        decoration: BoxDecoration(color: Colors.blue),
                      ),
                    ),
                    Text('$result')
                  ],
                  ),
              ))),
    );
  }

  bool isWordAndDigit(String value) {
    return RegExp(r"^[A-Za-z0-9_]+$").hasMatch(value);
  }
}
呈現效果 https://github.com/fenturechance/flutterPractice2021/tree/dd5aebd424e2f5ce7160fd41e8f96126eb5f4c1d

沒有留言:

張貼留言