Created with <3 with dartpad.dev.
Created
October 17, 2023 16:14
-
-
Save pjbelo/96ade6071bd212359a644325157b9865 to your computer and use it in GitHub Desktop.
Double-number-input-demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Demo2 for double number input | |
// only accepts minus sign at first position | |
import 'package:flutter/material.dart'; | |
import 'package:flutter/services.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return const MaterialApp( | |
home: MyDemo(), | |
); | |
} | |
} | |
class MyDemo extends StatefulWidget { | |
const MyDemo({ | |
Key? key, | |
}) : super(key: key); | |
@override | |
State<MyDemo> createState() => _MyDemoState(); | |
} | |
class _MyDemoState extends State<MyDemo> { | |
double? _myDoubleNumber; | |
final RegExp _myPattern = RegExp(r'^-?[\d,.]*$'); | |
void _updateMyDoubleNumber(value) { | |
setState(() { | |
_myDoubleNumber = double.tryParse(value); | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text("Your number is: ${_myDoubleNumber ?? "invalid number!"}"), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.start, | |
children: [ | |
Padding( | |
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16), | |
child: TextField( | |
decoration: const InputDecoration( | |
border: OutlineInputBorder(), | |
hintText: 'Enter a number', | |
), | |
keyboardType: | |
const TextInputType.numberWithOptions(decimal: true), | |
inputFormatters: [ | |
TextInputFormatter.withFunction( | |
(TextEditingValue oldValue, TextEditingValue newValue) { | |
return _myPattern.hasMatch(newValue.text) | |
? newValue | |
: oldValue; | |
}, | |
), | |
], | |
onChanged: (value) => _updateMyDoubleNumber(value), | |
), | |
) | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment