Search code examples
flutterdart

Create custom textformfield


I am trying to create custom textformfield so I can easily style only in one place. But currently I am stuck on how to pass validation and save process. Can someone give me a working example of custom widget textformfield that I can use? I have been searching it for whole day and cannot find one. Thank you for help.

Example here is on raised button:

import 'package:flutter/material.dart';
import 'package:wkndr/resources/constants.dart';

class CustomButton extends StatelessWidget {
  CustomButton({@required this.text, @required this.onPressed});

  final String text;
  final GestureTapCallback onPressed;

  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      color: colorPrimary,
      child: Text(text, style: TextStyle(fontSize: 17.0, color: colorWhite)),
      onPressed: onPressed,
      shape: new RoundedRectangleBorder(
          borderRadius: new BorderRadius.circular(30.0)),
    );
  }
}

Calling custom raised button:

final _signUpButton = Container(
      child: CustomButton(
          text: sign_up,
          onPressed: () {
            _signUp();
          }),
    );

Solution

  • Instead of making custom TextFormField, you can create a common InputDecoration for styling

    class CommonStyle {
      static InputDecoration textFieldStyle({
        String labelTextStr = "",
        String hintTextStr = "",
      }) {
        return InputDecoration(
          contentPadding: EdgeInsets.all(12),
          labelText: labelTextStr,
          hintText: hintTextStr,
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10),
          ),
        );
      }
    }

    Example:

    TextFormField(
      controller: usernameController,
      keyboardType: TextInputType.text,
      textInputAction: TextInputAction.next,
      focusNode: userFocus,
      onFieldSubmitted: (_) {
        FocusScope.of(context).requestFocus(passFocus);
      },
      validator: (value) => emptyValidation(value),
      decoration: CommonStyle.textFieldStyle(
        labelTextStr: "Username",
        hintTextStr: "Enter Username",
      ),
    )