Flutter:如何在TextEditingValue的中间输入数字

时间:2018-10-23 23:25:27

标签: flutter

我有以下要求:

  1. TextFormFields中有三个Column
  2. 前两个是加倍的小数点后两位。
  3. 第三个只是一个String字段,没有特殊限制。
  4. 当该字段获得焦点时,两个双字段应自动选择最后3位数字,以便用户可以开始为该字段输入新数字。 (在这种情况下,通常只有后3位数字会发生变化。)
  5. 用户没有按小数点,但是结果数字始终有两个小数位。
  6. 填写字段应自动前进到下一个字段。
  7. 用户应该能够将光标放置在任意两个数字之间,并开始在中间输入新的数字。例如,从458.90开始,用户可以将光标置于5后面并键入67以产生45678.90
  8. 当屏幕首次出现时,第一个字段自动对焦。 (反过来,这意味着最后三位数字已被选择。)

大多数要求都得到满足,但是我在第7条要求中苦苦挣扎。如何确定当前光标位置,以便在用户键入时将其前进一个位置(而不是跳到最后)?

下面的简单代码演示了此问题:

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

void main() => runApp(new MyApp());

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

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  static final _controller1 = TextEditingController();
  static final _controller2 = TextEditingController();
  final _focusNode1 = FocusNode();
  final _focusNode2 = FocusNode();
  final _focusNode3 = FocusNode();
  final _decimalFormatter = DecimalNumberTextInputFormatter(2);
  final _keyboardType = TextInputType.numberWithOptions(decimal: true);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: Column(children: [
        myTextFormField1(),
        myTextFormField2(),
        TextFormField(
          focusNode: _focusNode3,
        ),
      ]),
    );
  }

  initState() {
    super.initState();

    _focusNode1.addListener(() {
      int _baseOffset = _controller1.text.length > 4 ? _controller1.text.length - 4 : 0;
      if (_focusNode1.hasFocus) {
        _controller1.selection = TextSelection(
          baseOffset: _baseOffset,
          extentOffset: _controller1.text.length,
        );
      }
    });

    _focusNode2.addListener(() {
      int _baseOffset = _controller2.text.length > 4 ? _controller2.text.length - 4 : 0;
      if (_focusNode2.hasFocus) {
        _controller2.selection = TextSelection(
          baseOffset: _baseOffset,
          extentOffset: _controller2.text.length,
        );
      }
    });
  }

  Widget myTextFormField1() {
    _controller1.text = '458.90';
    return TextFormField(
      autofocus: true,
      focusNode: _focusNode1,
      controller: _controller1,
      onFieldSubmitted: (String value) {
        FocusScope.of(context).requestFocus(_focusNode2);
      },
      keyboardType: _keyboardType,
      inputFormatters: [_decimalFormatter],
      textInputAction: TextInputAction.next,
    );
  }

  Widget myTextFormField2() {
    _controller2.text = '123.45';
    return TextFormField(
      autofocus: false,
      focusNode: _focusNode2,
      controller: _controller2,
      onFieldSubmitted: (String value) {
        FocusScope.of(context).requestFocus(_focusNode3);
      },
      keyboardType: _keyboardType,
      inputFormatters: [_decimalFormatter],
      textInputAction: TextInputAction.next,
    );
  }

  @override
  void dispose() {
    _controller1.dispose();
    _controller2.dispose();
    super.dispose();
  }
}

class DecimalNumberTextInputFormatter extends TextInputFormatter {
  final int _decimalPlaces;

  DecimalNumberTextInputFormatter(this._decimalPlaces);

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    final String stripped = newValue.text.replaceAll(',', '').replaceAll('.', '');
    final int intNum = int.tryParse(stripped);
    if (intNum == null) {
      return oldValue;
    }
    final dblNum = intNum / pow(10, _decimalPlaces);
    final String newString = dblNum.toStringAsFixed(_decimalPlaces);
    if (newValue.text.compareTo(oldValue.text) == 0) {
      return newValue;
    } else if (double.parse(newValue.text) == 0.0) {
      return TextEditingValue(text: '');
    }
    return TextEditingValue(
      text: newString,
      selection: TextSelection(
        baseOffset: newString.length,   //TODO: Need the old cursor location + 1 here
        extentOffset: newString.length, //TODO: Need the old cursor location + 1 here
      ),
    );
  }
}

顺便说一句,我也欢迎提出简化此代码的建议。似乎可能是DRYer:)

感谢您的任何建议...

0 个答案:

没有答案