Search code examples
flutterflutter-iosflutter-androidflutter-textinputfield

Is it possible to create a text field phone number mask which is not disappearing when user inputs, in flutter?


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.


Solution

  • 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