如何解决这个问题textfield在flutter中获取值

问题描述 投票:0回答:2
@override
  Widget build(BuildContext context) {
    final AppStateManager manager = AppStateManager.of(context);

    String textLetter = manager.appState.replacementsController.text;
    String textCodeElec = manager.appState.replacementsController.value.text;
    log('data: ${manager.appState.textEditingDeltaHistory.length}');

    if (textLetter == 'a' || textLetter == 'A') {
      textCodeElec = '90'; //a print 90
    }
    if (textLetter == 'b' || textLetter == 'B') {
      textCodeElec = '88';// b print 88
    }
    if (textLetter == 'ao' || textLetter == 'Ao') {
      textCodeElec = '94';// but bao print bao are not 88 94
    }
    // log('textLetter: ${textLetter}');
    log('textCodeElec: ${textCodeElec}');
    return Column(
      children: [
        _buildTextEditingDeltaViewCode(textCodeElec),
        _buildTextEditingDeltaViewHeader(),
        Expanded(
          child: ListView.separated(
            padding: const EdgeInsets.symmetric(horizontal: 35.0),
            itemBuilder: (context, index) {
              return _buildTextEditingDeltaHistoryViews(
                  manager.appState.textEditingDeltaHistory)[index];
            },
            itemCount: manager.appState.textEditingDeltaHistory.length,
            separatorBuilder: (context, index) {
              return const SizedBox(height: 2.0);
            },
          ),
        ),
        const SizedBox(height: 10),
      ],
    );
  }

我尝试了很多方法,但当b = 88,ao = 94但'bao = bao'不是'bao = 88 94'时仍然没有按要求显示。

接下来我可以尝试什么?

flutter textfield
2个回答
0
投票

你的目标

当用户输入文本时,它应该测试它是否以某些关键字符(a,b,ao)开头,如果是这种情况,它应该添加到textCodeElec一个数字,检查其余值是否等于其他关键角色,如果是的话添加它们。

例子:

  • 对于 b 它应该返回 88
  • 对于 bao 应该返回 88 94
  • 对于 aao 它应该返回 90 94

不起作用的原因

在您的条件下,您使用的是“==”比较器,因此当您键入“bao”时,它不等于“b”或“ao”,这就是它返回相同值的原因。

解决方案

要解决这个问题,您可以使用 startsWith 来检查值是否以关键字符开头,如果是这种情况,您将获取该键的值,然后检索该文本的键,以便您可以使用下一个键进行测试价值观。

if (textLetter.toLowerCase().startsWith('a')) {
      textCodeElec += ' 90'; //a print 90
      // remove a from textLetter
      textLetter = textLetter.substring(1);
}
if (textLetter.toLowerCase().startsWith('b')) {
      textCodeElec += ' 88';// b print 88
      // remove b from textLetter
      textLetter = textLetter.substring(1);
}
if (textLetter.toLowerCase().startsWith('ao')) {
      textCodeElec += ' 94';// but bao print bao are not 88 94
      // remove ao from textLetter
      textLetter = textLetter.substring(2);
}

//remove all spaces at the beginning and at the end
textCodeElec = textCodeElec.trim();

0
投票

bao
b
ao
是不同的值。 如果你想在值为
88 94
时显示
bao
那么你应该添加:

if (textLetter == 'bao' || textLetter == 'Bao') {
  textCodeElec = '88 94';
}

您的代码。

© www.soinside.com 2019 - 2024. All rights reserved.