Home > OS >  How to implement Flutter TextFormField validator with GetX?
How to implement Flutter TextFormField validator with GetX?

Time:10-09

I am trying to implement TextFormField validation with GetxController, but validator doesn't show anything. I assume it is null. Could anybody help me on this?

Here's the whole code below related to my question.

I found that TextFormField validation works with StatefulWidget, but I just want to implement it with Getx.

auth_controller.dart

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

class AuthController extends GetxController {
  final formKey = GlobalKey<FormState>();
  String userEmail = '';
  String userName = '';
  String userPassword = '';

  String? emailValidator(String value) {
    if (value.isEmpty || !value.contains('@')) {
      return 'Please enter a valid email address.';
    }
    return null;
  }

  String? userNameValidator(String value) {
    if (value.isEmpty || value.length < 4) {
      return 'Password must be at least 4 characters long.';
    }
    return null;
  }

  String? passwordValidator(String value) {
    if (value.isEmpty || value.length < 7) {
      return 'Password must be at least 7 characters long.';
    }
    return null;
  }

  void trySubmit() {
    final isValid = formKey.currentState!.validate();
    Get.focusScope!.unfocus();

    if (isValid) {
      formKey.currentState!.save();
      print(userEmail);
      print(userName);
      print(userPassword);

      // User those values to send our auth request ...
    }
  }
}

auth_form.dart

import 'package:chatting_app/controllers/auth_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class AuthForm extends GetView<AuthController> {
  AuthForm({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Card(
        margin: EdgeInsets.all(20),
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(16),
            child: Form(
              key: controller.formKey,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TextFormField(
                    validator: (value) {
                      controller.emailValidator(value!);
                    },
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(
                      labelText: 'Email address',
                    ),
                    onSaved: (value) {
                      controller.userEmail = value!;
                    },
                  ),
                  TextFormField(
                    validator: (value) {
                      controller.userNameValidator(value!);
                    },
                    decoration: InputDecoration(labelText: 'Username'),
                    onSaved: (value) {
                      controller.userName = value!;
                    },
                  ),
                  TextFormField(
                      validator: (value) {
                        controller.passwordValidator(value!);
                      },
                      decoration: InputDecoration(labelText: 'Password'),
                      obscureText: true,
                      onSaved: (value) {
                        controller.userPassword = value!;
                      }),
                  SizedBox(height: 12),
                  ElevatedButton(
                    child: Text('Login'),
                    style: ElevatedButton.styleFrom(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20.0),
                      ),
                      primary: Colors.pink,
                      onPrimary: Colors.white,
                    ),
                    onPressed: controller.trySubmit,
                  ),
                  TextButton(
                    child: Text('Create new account'),
                    style: TextButton.styleFrom(
                      primary: Colors.pink,
                    ),
                    onPressed: () {},
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

auth_screen.dart

import 'package:chatting_app/widgets/auth/auth_form.dart';
import 'package:flutter/material.dart';

class AuthScreen extends StatelessWidget {
  const AuthScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).primaryColor,
      body: AuthForm(),
    );
  }
}

binding.dart

import 'package:chatting_app/controllers/auth_controller.dart';
import 'package:get/get.dart';

class Binding implements Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => AuthController());
  }
}

main.dart

import 'package:chatting_app/bindings/binding.dart';
import 'package:chatting_app/screens/auth_screen.dart';
import 'package:chatting_app/screens/chat_screen.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Chatting App',
      theme: ThemeData(
        primarySwatch: Colors.pink,
        backgroundColor: Colors.pink,
        colorScheme:
            ColorScheme.fromSwatch(primarySwatch: Colors.pink).copyWith(
          secondary: Colors.deepPurple,
        ),
        visualDensity: VisualDensity.adaptivePlatformDensity,
        buttonTheme: ButtonTheme.of(context).copyWith(
          buttonColor: Colors.pink,
          textTheme: ButtonTextTheme.primary,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
        ),
      ),
      initialBinding: Binding(),
      initialRoute: '/',
      getPages: [
        GetPage(name: '/', page: () => AuthScreen()),
      ],
    );
  }
}

CodePudding user response:

You should change like below;

Your Code:

TextFormField(
                    validator: (value) {
                      controller.emailValidator(value!);
                    },
...

Should be:

TextFormField(
                    validator: (value) {
                      return controller.emailValidator(value!);
                    },
...

or

TextFormField(
                    validator: controller.emailValidator(value!),
...
  • Related