使用TextSelection将光标置于TextField的末尾

时间:2020-05-22 17:47:53

标签: flutter

我想对TextField进行简单的验证。 我的方法是听TextField的{​​{1}}事件,应用我的验证,将值设置为onChange,并将controller.text设置为先前设置的值的长度。

Dartpad

由于123456789输入的原因,controller.selection产生864213579。在写入即将到来的字符时,在开始和结尾之间交替。使用TextField,我可以断言选择应该始终在输入的末尾。

这里可能是什么问题?

1 个答案:

答案 0 :(得分:0)

为什么不使用TextInputFormatter?

这是代码。

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var controller = TextEditingController();
  final _amountValidator = RegExInputFormatter.withRegex('^\$|^(0|([1-9][0-9]{0,}))(\\.[0-9]{0,})?\$');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(''),
      ),
      body: Builder(
        builder: (context) {
          return 
            Column(
          children: <Widget>[
            TextField(
            inputFormatters: [_amountValidator],
            controller: controller,
            keyboardType: TextInputType.numberWithOptions(
              decimal: true,
              signed: false,
            ),           
          ),
            FlatButton(
              onPressed:(){
                print(controller.text);
              },
              child:Text("Test"),
            )
            ],
          );
        },
      ),
    );
  }
}






class RegExInputFormatter implements TextInputFormatter {
  final RegExp _regExp;

  RegExInputFormatter._(this._regExp);

  factory RegExInputFormatter.withRegex(String regexString) {
    try {
      final regex = RegExp(regexString);
      return RegExInputFormatter._(regex);
    } catch (e) {
      // Something not right with regex string.
      assert(false, e.toString());
      return null;
    }
  }

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    final oldValueValid = _isValid(oldValue.text);
    final newValueValid = _isValid(newValue.text);
    if (oldValueValid && !newValueValid) {
      return oldValue;
    }
    return newValue;
  }

  bool _isValid(String value) {
    try {
      final matches = _regExp.allMatches(value);
      for (Match match in matches) {
        if (match.start == 0 && match.end == value.length) {
          return true;
        }
      }
      return false;
    } catch (e) {
      // Invalid regex
      assert(false, e.toString());
      return true;
    }
  }
}

REF:Flutter TextField input only decimal numbers