【问题标题】:Changing the text characters as user is typing in textfield flutter当用户在文本字段中输入时更改文本字符
【发布时间】:2021-05-27 20:32:22
【问题描述】:

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

我的代码中现在有这个:

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

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

【问题讨论】:

  • 你试过使用TextField的onChanged吗?

标签: flutter dart flutter-textinputfield


【解决方案1】:

我建议为此使用 TextInputFormatter。

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

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

【讨论】:

    【解决方案2】:

    您可以通过传入一个接受新文本作为参数的函数来使用文本字段的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-01-28
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      相关资源
      最近更新 更多