1

Is it possible to create phone number mask like this in flutter: mask example

When user input numbers, mask is staying, and numbers of the mask are replacing with user's input.

2 Answers2

2

Stack 2 TextFields one for the hint and one for the user input and remove the string in hint when the user inputs some values like this

import 'package:flutter/material.dart';

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

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: const MyHomePage(),
    );
  }
}

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController hintController = TextEditingController();
  static String hintVal = "987654321";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    hintController.text = hintVal;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: Stack(
        children: [
          IgnorePointer(
            child: TextField(
              controller: hintController,
              style: TextStyle(color: Colors.grey),
            ),
          ),
          TextField(
            onChanged: (val) {
              String newHint = "";
              for (int i = 0; i < hintVal.length; i++) {
                if (i < val.length) {
                  newHint += val[i];
                } else {
                  newHint += hintVal[i];
                }
              }
              hintController.text = newHint;
            },
          ),
        ],
      )),
    );
  }
}

preview

Kaushik Chandru
  • 15,510
  • 2
  • 12
  • 30
  • I had the same idea, but I thought flutter has a more elegant solution. Thanks for help! – shamiwizard Jun 18 '22 at 18:45
  • There is no option to hold the hint text if the textfield is filled. There are some packages but it only formats the input not display a text behind while you type – Kaushik Chandru Jun 18 '22 at 18:51
0

you can use prefix widget or into onChange textField method like below code handle it:

final c = TextEditingController();
bool x = true;

TextFormField(
      controller: c,
      onChanged: (val) {
        if (x) {
          x = false;
          c.text = '99'+val;
        } else if (val.length == 0) x = true;
      },
    )
Hossein Asadi
  • 768
  • 1
  • 6
  • 15