0

我是 Flutter 的新手,我正在尝试找出一种方法,以便用户可以在我的应用程序中以非常具体的方式输入他们的代词。例如,他们可以键入“she/her/hers”,如果按空格键,则会出现“/”。我目前有一个文本字段,但我不确定从哪里开始以及它如何工作。

我现在在我的代码中有这个:

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

但它不起作用。任何帮助将非常感激。谢谢!

4

2 回答 2

0

您可以onChanged通过传入一个接受新文本作为参数的函数来使用文本字段的属性。尝试这个:

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,
              );
            }
          ),
        ),
      ),
    );
  }
}
于 2021-05-27T21:07:44.533 回答
0

我建议为此使用 TextInputFormatter。

看看https://api.flutter.dev/flutter/services/TextInputFormatter-class.html

“要创建自定义格式化程序,请扩展 TextInputFormatter 类并实现 formatEditUpdate 方法。”

于 2021-05-27T20:51:49.027 回答