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.
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.
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;
},
),
],
)),
);
}
}
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;
},
)