Flutter TextField 值始终大写和去抖动

问题描述 投票:0回答:14

我是 Flutter 的新手。我正在寻找始终大写的 TextField 值,但我没有找到任何相关资源。

另一个问题是 TextField onChanged 事件去抖实现。当我在 TextField 上键入时,它会立即触发 onChanged 事件,这不适合我的目标。 onChange 事件将在每次文本更改 500 毫秒后触发。

 new TextField(
         controller: _controller,
         decoration: new InputDecoration(
              hintText: 'Search here',
         ),
         onChanged: (str) {
            //need to implement debounce
         }
)
flutter dart textfield uppercase debouncing
14个回答
201
投票

适用于 Android、iOS、Web、macOS、Windows 和 Linux

您可以实现自定义

TextInputFormatter

class UpperCaseTextFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    return TextEditingValue(
      text: newValue.text.toUpperCase(),
      selection: newValue.selection,
    );
  }
}

用法:

TextField(
  inputFormatters: [
    UpperCaseTextFormatter(),
  ]
)

完整示例


107
投票

也许在 TextField 中使用 textCapitalization: TextCapitalization.characters 可以帮助你?尽管这也会在输入内容时将字符大写。

TextField(
    textCapitalization: TextCapitalization.sentences,
)

49
投票

您可以使用

textCapitalization
小部件的
TextField
属性。也请参考这里的详细 API 信息Text Capitalization Official API

图示如下

例一

 TextField(
        initialValue: flutter code camp
        textCapitalization: TextCapitalization.characters,
    )// OUTPUT : FLUTTER CODE CAMP

例二

 TextField(
        initialValue: flutter code camp
        textCapitalization: TextCapitalization.words,
    )// OUTPUT : Flutter Code Camp

示例 3

 TextField(
        initialValue: flutter code camp
        textCapitalization: TextCapitalization.sentences,
    )// OUTPUT : Flutter code camp

示例 4

 TextField(
        initialValue: flutter code camp
        textCapitalization: TextCapitalization.none,
    )// OUTPUT : flutter code camp

28
投票

您需要做的是:

字符串放置后

.toUpperCase()

例子:

"Some text".toUpperCase()

这在我的案例中有效。我也是新手,所以我希望我能帮到你。


18
投票

您可以使用

TextCapitalization.characters
使所有键入的字符大写

TextField(
    textCapitalization: TextCapitalization.characters,
)

8
投票

@Günter-Zöchbauer 的解决方案有效,但是当您在 Android 上切换到数字键盘时,如果您键入一个,它会再次切换到字母键盘。

这是因为您每次都设置了一个新的 TextEditingValue。

相反,如果您复制最新的并更改文本,它会起作用:

import 'package:flutter/services.dart';

class UpperCaseTextFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    return newValue.copyWith(text: newValue.text.toUpperCase());
  }
}

7
投票

最简单的方法是添加 TextField 的 onChanged 事件,并使用 TextField 的控制器将其转换为大写,就像上面一样:

TextField(
          controller: controllerReservation,
          onChanged: (value) {               
            controllerReservation.value = 
               TextEditingValue(
                                text: value.toUpperCase(), 
                                selection: controllerReservation.selection);
          },
        )

6
投票

TextField 有一个 textCapitalization 属性,您可以使用它来大写单词、句子或字符

如果您想将文本输入的全部价值大写,请使用

TextField(
  textCapitalization: TextCapitalization.characters,
 )

2
投票

以下是如何实现对输入文本的去抖动(或延迟)效果:

1) 导入包

rxdart: ^0.18.1 (or whatever the version will be)

2) 在您的有状态小部件中声明以下

final subject = new PublishSubject<String>();

3) 在同一个Stateful Widget中,在initState方法下声明如下

subject.stream
    .debounce(new Duration(milliseconds: 500))
    .listen(_loadNewData);

4) 在同一个 Stateful Widget 中,创建以下方法(将在 500 毫秒后触发)

  void _loadNewData(String newData) {
    //do update here
  }

4) 将以下行添加到您的 Textfield Widget(您现在可以摆脱 Controller)

onChanged: (string) => (subject.add(string)),

1
投票
TextField(
  controller: textController,
    onChanged: (value) {
      if (textController.text != value.toUpperCase())
        textController.value = textController.value.copyWith(text: value.toUpperCase());
  },
)

1
投票

将此添加到您的

TextFormField

 inputFormatters: [UpperCaseTextFormatter()],
 textCapitalization: TextCapitalization.characters,

完整代码

  TextFormField(
      autofillHints: [AutofillHints.name],
      inputFormatters: [UpperCaseTextFormatter()],
      textCapitalization: TextCapitalization.characters,
      textInputAction: TextInputAction.next,
      style: TextStyle(fontSize: 20),
      decoration: InputDecoration(
      contentPadding: EdgeInsets.symmetric(
      horizontal: 0, vertical: 0),
      labelText: "Hello World",
      hintText: '',
    ),
 ),

0
投票

 textCapitalization: TextCapitalization.characters,

简单!


0
投票

这适用于所有平台:

TextEditingController mytext = TextEditingController();
TextField(
  controller: mytext,
  onChanged: (value) {
    mytext.value = TextEditingValue(
      text: value.toUpperCase(), 
      selection: mytext.selection,
    );
  },
)

-1
投票

这是一个实用类,可以帮助它:

 class TextCapitalizationFormatter extends TextInputFormatter {
      final TextCapitalization capitalization;

  TextCapitalizationFormatter(this.capitalization);

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    String text = '';

    switch (capitalization) {
      case TextCapitalization.words:
        text = capitalizeFirstofEach(newValue.text);
        break;
      case TextCapitalization.sentences:
        List<String> sentences = newValue.text.split('.');
        for (int i = 0; i < sentences.length; i++) {
          sentences[i] = inCaps(sentences[i]);
          print(sentences[i]);
        }
        text = sentences.join('.');
        break;
      case TextCapitalization.characters:
        text = allInCaps(newValue.text);
        break;
      case TextCapitalization.none:
        text = newValue.text;
        break;
    }

    return TextEditingValue(
      text: text,
      selection: newValue.selection,
    );
  }

  /// 'Hello world'
  static String inCaps(String text) {
    if (text.isEmpty) {
      return text;
    }
    String result = '';
    for (int i = 0; i < text.length; i++) {
      if (text[i] != ' ') {
        result += '${text[i].toUpperCase()}${text.substring(i + 1)}';
        break;
      } else {
        result += text[i];
      }
    }
    return result;
  }

  /// 'HELLO WORLD'
  static String allInCaps(String text) => text.toUpperCase();

  /// 'Hello World'
  static String capitalizeFirstofEach(String text) => text
      .replaceAll(RegExp(' +'), ' ')
      .split(" ")
      .map((str) => inCaps(str))
      .join(" ");
}

用法:

TextField(
  inputFormatters: [
    TextCapitalizationFormatter(TextCapitalization.sentences),
  ]
)
© www.soinside.com 2019 - 2024. All rights reserved.