一統天下 flutter - widget 文本類: Form - 表單

源碼 https://github.com/webabcd/flutter_demo
作者 webabcd

一統天下 flutter - widget 文本類: Form - 表單

示例如下:

lib\widget\text\form.dart

/*
 * Form - 表單
 */

import 'package:flutter/material.dart';
import 'package:flutter_demo/helper.dart';

class FormDemo extends StatefulWidget {
  const FormDemo({Key? key}) : super(key: key);

  @override
  _FormDemoState createState() => _FormDemoState();
}

class _FormDemoState extends State<FormDemo> {

  /// 用於驗證指定的表單是否合法
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("title"),),
      backgroundColor: Colors.orange,
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            /// 表單元素有 TextFormField, InputDatePickerFormField, DropdownButtonFormField 等
            TextFormField(
              decoration: const InputDecoration(
                hintText: 'hintText',
              ),
              /// 用於驗證當前輸入是否合法
              validator: (String? value) {
                if (value == null || value.isEmpty) {
                  /// 不合法,返回錯誤的提示信息
                  return "請輸入內容";
                }
                /// 合法
                return null;
              },
            ),
            TextFormField(
              decoration: const InputDecoration(
                hintText: 'hintText',
              ),
              validator: (String? value) {
                if (value == null || value.isEmpty || value.length <= 10) {
                  return "輸入內容的字符數要大於 10";
                }
                return null;
              },
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: ElevatedButton(
                onPressed: () {
                  /// 驗證表單是否合法
                  if (_formKey.currentState!.validate()) {
                    log("已通過驗證");
                  } else {
                    log("未通過驗證");
                  }
                },
                child: const Text('提交'),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

源碼 https://github.com/webabcd/flutter_demo
作者 webabcd

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章