Skip to content

Instantly share code, notes, and snippets.

@sorgfal
Last active June 16, 2023 14:12
Show Gist options
  • Select an option

  • Save sorgfal/0ccfb483d622af89e3d2b50804263d0c to your computer and use it in GitHub Desktop.

Select an option

Save sorgfal/0ccfb483d622af89e3d2b50804263d0c to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late final TextControllerCustomView _controller;
@override
void initState() {
_controller = TextControllerCustomView();
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: Center(
child: TextFieldExample(
controller: _controller,
),
),
));
}
}
class TextFieldExample extends StatelessWidget {
final TextControllerCustomView controller;
const TextFieldExample({super.key, required this.controller});
@override
Widget build(BuildContext context) {
return TextField(
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r"(^\d*\.?\d*)")),
TextInputFormatter.withFunction((oldValue, newValue) {
var miv = MoneyInputValue(newValue.text);
return miv.man().length <= 2 ? newValue : oldValue;
})
],
keyboardType: TextInputType.numberWithOptions(decimal: true),
controller: controller,
style: TextStyle(fontSize: 12),
);
}
}
class TextControllerCustomView extends TextEditingController {
@override
TextSpan buildTextSpan(
{required BuildContext context,
TextStyle? style,
required bool withComposing}) {
var miv = MoneyInputValue(super.text);
return TextSpan(children: [
TextSpan(
text: '${miv.exp(fractionDigits: 2)}.',
style: style?.copyWith(fontSize: (style.fontSize ?? 0) + 2)),
TextSpan(text: miv.man(fractionDigits: 2), style: style)
]);
}
}
class MoneyInputValue {
final String text;
MoneyInputValue(this.text);
double parseValue() {
double? d = double.tryParse(text);
return d ?? 0;
}
List<String> getNumberParts({int? fractionDigits}) {
String td = fractionDigits == null
? parseValue().toString()
: parseValue().toStringAsFixed(fractionDigits);
return td.split('.');
}
String exp({int? fractionDigits}) =>
getNumberParts(fractionDigits: fractionDigits).first;
String man({int? fractionDigits}) =>
getNumberParts(fractionDigits: fractionDigits).last;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment