Changing the text characters as user is typing in textfield flutter

1.1k views Asked by At

I'm new to flutter and I'm trying to figure out a way so that users can type their pronouns in a very specific way into my app. They can type "she/her/hers" for example, and if they press space, a "/" would appear. I currently have a textfield for this but I'm not sure where to proceed and how it could work.

I have this in my code right now:

  String _textSelect(String _controller) {
    _controller = _controller.replaceAll(" ", "/");
    return str;
  }

But it doesn't work. Any help would be really appreciated. Thank you!

2

There are 2 answers

0
SuPythony On

You can use the onChanged property of text field by passing in a function that accepts the new text as a paramter. Try this:

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  
  final _textController = TextEditingController();
  
  @override
  void dispose() {
    _textController.dispose();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: TextField(
      controller: _textController,
      onChanged: (text) {
        _textController.text = text.replaceAll(" ", "/");
       _textController.value = _textController.value.copyWith(
        selection:
            TextSelection(baseOffset: text.length, extentOffset: text.length),
        composing: TextRange.empty,
              );
            }
          ),
        ),
      ),
    );
  }
}
0
Robert Sandberg On

I would recommend using a TextInputFormatter for that.

Have a look at https://api.flutter.dev/flutter/services/TextInputFormatter-class.html

"To create custom formatters, extend the TextInputFormatter class and implement the formatEditUpdate method."