gpt4 book ai didi

flutter - 为什么Android在iOS上不能在TextField中显示正确格式的文本?

转载 作者:行者123 更新时间:2023-12-03 03:36:30 25 4
gpt4 key购买 nike

最小代码:

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

void main() => runApp(MaterialApp(home: MyPage()));

class MyPage extends StatelessWidget {
final _controller = TextEditingController(text: "");

@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(44.0),
child: Center(
child: TextField(
controller: _controller,
keyboardType: TextInputType.number,
onChanged: (string) {
string = string.replaceAll(RegExp(","), "");
string = _formattedString(string);
_controller.text = string;
_controller.selection = TextSelection.fromPosition(TextPosition(offset: string.length));
},
),
),
),
);
}

_formattedString(string) {
final format = NumberFormat.decimalPattern();
return format.format(int.parse(string));
}
}

在Android和iOS上运行此代码,在android中输入类似 123456789的数字,它会打印出一些奇怪的序列,但在iOS上确实有效。谁能告诉我代码有什么问题吗?

Android输出

enter image description here

iOS输出

enter image description here

最佳答案

或者,如果您不希望项目中存在其他依赖项,请尝试以下方法:

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

void main() => runApp(MaterialApp(home: MyPage()));

class NumericTextFormatter extends TextInputFormatter {
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.text.length == 0) {
return newValue.copyWith(text: '');
} else if (newValue.text.compareTo(oldValue.text) != 0) {
int selectionIndexFromTheRight = newValue.text.length - newValue.selection.end;
final f = new NumberFormat("#,###");
int num = int.parse(newValue.text.replaceAll(f.symbols.GROUP_SEP, ''));
final newString = f.format(num);
return new TextEditingValue(
text: newString,
selection: TextSelection.collapsed(offset: newString.length - selectionIndexFromTheRight),
);
} else {
return newValue;
}
}
}

class MyPage extends StatelessWidget {
final _controller = TextEditingController(text: "");

@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(44.0),
child: Center(
child: TextField(
controller: _controller,
keyboardType: TextInputType.number,
inputFormatters: [NumericTextFormatter()],
),
),
),
);
}
}

信用归功于: https://stackoverflow.com/a/51739086/5235984

关于flutter - 为什么Android在iOS上不能在TextField中显示正确格式的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60659932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com