Flutter表单验证插件nik_validator的使用

发布于 1周前 作者 zlyuanteng 来自 Flutter

Flutter表单验证插件nik_validator的使用

nik_validator 是一个用于解析印度尼西亚身份证号码(NIK)的Flutter包,它能将NIK转换为有用的信息。只需调用.parse函数并输入NIK号码作为参数,即可获取信息,且无需网络连接(离线)。以下是关于如何在Flutter项目中使用此插件的详细说明和示例代码。

添加依赖

首先,在pubspec.yaml文件中添加nik_validator依赖:

dependencies:
  flutter:
    sdk: flutter
  nik_validator: ^latest_version # 替换为最新版本号

然后执行flutter pub get以安装依赖。

示例代码

下面是一个完整的Flutter应用程序示例,演示了如何使用nik_validator来验证和解析NIK。

main.dart

import 'package:flutter/material.dart';
import 'package:nik_validator/nik_validator.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'NIK Validator',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.blue,
          title: Text("NIK Validator"),
        ),
        body: HomePage(),
      ),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final nikController = TextEditingController();
  NIKModel? nikResult;

  /// Validate NIK information
  void validate() async {
    if (nikController.text.isNotEmpty) {
      NIKModel result = await NIKValidator.instance.parse(nik: nikController.text);
      setState(() {
        nikResult = result;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;

    return Center(
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 20),
        width: width,
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _fieldNIK(),
              _buttonParse(),
              SizedBox(height: 20),
              nikResult != null
                  ? _resultWidget()
                  : SizedBox(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _resultWidget() {
    double width = MediaQuery.of(context).size.width;

    return Container(
      width: width,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.black)
      ),
      child: Padding(
        padding: const EdgeInsets.all(10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _textWidget(
              title: "NIK",
              value: nikResult!.nik!
            ),
            Divider(color: Colors.black),
            _textWidget(
              title: "Unique Code",
              value: nikResult!.uniqueCode!
            ),
            Divider(color: Colors.black),
            _textWidget(
              title: "Gender",
              value: nikResult!.gender!
            ),
            Divider(color: Colors.black),
            _textWidget(
              title: "Birth Date",
              value: nikResult!.bornDate!
            ),
            Divider(color: Colors.black),
            _textWidget(
              title: "Age",
              value: nikResult!.age!
            ),
            Divider(color: Colors.black),
            _textWidget(
              title: "Next Birthday",
              value: nikResult!.nextBirthday!
            ),
            Divider(color: Colors.black),
            _textWidget(
              title: "Zodiac",
              value: nikResult!.zodiac!
            ),
            Divider(color: Colors.black),
            _textWidget(
              title: "Province",
              value: nikResult!.province!
            ),
            Divider(color: Colors.black),
            _textWidget(
              title: "City/District",
              value: nikResult!.city!
            ),
            Divider(color: Colors.black),
            _textWidget(
              title: "Subdistrict",
              value: nikResult!.subdistrict!
            ),
            Divider(color: Colors.black),
            _textWidget(
              title: "Postal Code",
              value: nikResult!.postalCode!
            ),
          ],
        ),
      ),
    );
  }

  Widget _textWidget({required String title, required String value}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
          child: Text(
            title,
            style: TextStyle(
              color: Colors.black,
              fontWeight: FontWeight.bold,
              fontSize: 18
            ),
          ),
        ),
        Expanded(
          child: Text(
            value,
            textAlign: TextAlign.end,
            style: TextStyle(
              color: Colors.black,
              fontSize: 18
            ),
          ),
        )
      ],
    );
  }

  Widget _fieldNIK() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        TextField(
          controller: nikController,
          textInputAction: TextInputAction.go,
          keyboardType: TextInputType.number,
          decoration: InputDecoration(
            hintText: "Enter NIK number",
            border: OutlineInputBorder(borderSide: BorderSide(color: Colors.blue)),
            labelText: "NIK"
          ),
        ),
        SizedBox(height: 5),
        nikResult != null && !nikResult!.valid
            ? Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "Invalid NIK code",
                  style: TextStyle(
                    color: Colors.red,
                    fontSize: 15
                  ),
                ),
                SizedBox(height: 5),
              ],
            )
            : SizedBox()
      ],
    );
  }

  Widget _buttonParse() {
    double width = MediaQuery.of(context).size.width;
    return Container(
      width: width,
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          primary: Colors.blue,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(5)
          ),
        ),
        onPressed: () => validate(),
        child: Text(
          "Validate NIK",
          style: TextStyle(
            color: Colors.white
          ),
        ),
      ),
    );
  }
}

关于我

如果您对nik_validator或任何其他问题有任何疑问,欢迎访问我的网站:leeyurani.com 或在我的GitHub上关注我:yusriltakeuchi

希望这个指南能帮助您成功地在Flutter应用中集成和使用nik_validator!如果有任何问题,请随时提问。


更多关于Flutter表单验证插件nik_validator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter表单验证插件nik_validator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter中使用nik_validator插件进行表单验证的代码示例。nik_validator是一个流行的Flutter插件,用于对表单输入进行验证,例如检查电子邮件格式、密码强度等。

首先,你需要在你的pubspec.yaml文件中添加nik_validator依赖项:

dependencies:
  flutter:
    sdk: flutter
  nik_validator: ^x.y.z  # 请将x.y.z替换为最新版本号

然后运行flutter pub get来安装依赖项。

接下来是一个完整的示例,展示了如何使用nik_validator进行表单验证:

import 'package:flutter/material.dart';
import 'package:nik_validator/nik_validator.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Form Validation Example'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: MyForm(),
        ),
      ),
    );
  }
}

class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}

class _MyFormState extends State<MyForm> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  late final NikValidator _nikValidator;

  @override
  void initState() {
    super.initState();
    _nikValidator = NikValidator(
      validations: {
        'email': {
          'isRequired': true,
          'isEmail': true,
        },
        'password': {
          'isRequired': true,
          'minLength': 6,
        },
      },
    );
  }

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  void _submitForm() async {
    if (_formKey.currentState!.validate()) {
      final Map<String, dynamic> values = {
        'email': _emailController.text,
        'password': _passwordController.text,
      };

      final result = await _nikValidator.validateFields(values);
      if (result.isValid) {
        // 提交表单数据
        print('Form is valid and ready to submit!');
      } else {
        // 显示错误信息
        result.errors.forEach((key, value) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text("${key.capitalize()}: ${value.join(", ")}"),
            ),
          );
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: [
          TextFormField(
            controller: _emailController,
            decoration: InputDecoration(labelText: 'Email'),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Email is required';
              }
              return null;
            },
          ),
          TextFormField(
            controller: _passwordController,
            decoration: InputDecoration(labelText: 'Password'),
            obscureText: true,
            validator: (value) {
              if (value == null || value.isEmpty || value.length < 6) {
                return 'Password must be at least 6 characters long';
              }
              return null;
            },
          ),
          SizedBox(height: 16),
          ElevatedButton(
            onPressed: _submitForm,
            child: Text('Submit'),
          ),
        ],
      ),
    );
  }
}

在这个示例中,我们定义了一个简单的表单,包含电子邮件和密码字段。我们使用TextFormField来创建这些字段,并设置了基本的验证逻辑。但是,实际的验证逻辑是通过nik_validator插件来完成的。

_submitForm方法中,我们首先检查表单的基本验证(通过Flutter的内置验证),然后使用nik_validator进行更详细的验证。如果验证通过,我们可以提交表单数据;如果验证失败,我们显示错误信息。

请注意,虽然我们在TextFormField中也设置了基本的验证器,但这些验证器主要用于即时反馈(当用户离开字段时)。nik_validator的验证是在提交表单时进行的,它提供了更复杂的验证逻辑。

希望这个示例对你有所帮助!

回到顶部