How to add country dial code to TextEditingController in flutter - flutter

I'm using flutter package country_code_picker into my TextFormField and i achieve to put users country dial code into my phone TextEditingController text after they select there country. So if for example in Senegal user put 7712345678, i will get +2217712345678 in my TextEditing controller text. Thanks in advance for help.
here is my code
TextEditingController phoneController = new TextEditingController(text: "");
Widget _phoneContainer() {
return new Container(
child: new TextFormField(
controller: phoneController,
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(vertical: 2),
prefixIcon: CountryCodePicker(
// Initial selection and favorite can be one of code ('IT') OR dial_code('+39')
initialSelection: '+221',
favorite: ['+221', 'SN'],
textStyle: TextStyle(color: Colors.orange[900]),
showFlag: true,
//showFlagDialog: true,
//comparator: (a, b) => b.name.compareTo(a.name),
//Get the country information relevant to the initial selection
//onInit: (code) => print("${code.name} ${code.dialCode}"),
),
labelText: Texts.PHONE_NUMBER_LOGIN,
focusColor: Colors.orange[900],
labelStyle: TextStyle(fontSize: 15.0, color: Colors.orange[900]),
/* hintStyle: TextStyle(
color: Colors.orange[900]
) */
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
borderSide: const BorderSide(color: Colors.white)
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
borderSide: const BorderSide(color: Colors.white)
),
hasFloatingPlaceholder: false
),
keyboardType: TextInputType.phone,
style:TextStyle(
color: Colors.orange[900],
decorationColor: Colors.white,
),
),
margin: EdgeInsets.only(bottom: 20.0, left: 40.0, right: 40.0),
color: Colors.white,
height: 40.0,
);
}

Run this code. On Check Button, it will print your whole phone number (dial code + entered phone number in text field) on console
import 'package:flutter/material.dart';
import 'package:country_code_picker/country_code_picker.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
TextEditingController phoneController = new TextEditingController();
String phoneNumber = "";
void _onCountryChange(CountryCode countryCode) {
this.phoneNumber = countryCode.toString();
print("New Country selected: " + countryCode.toString());
}
void check(){
print("Full Text: "+ this.phoneNumber + phoneController.text);
}
#override
Widget build(BuildContext context) {
final phone = new TextFormField(
controller: phoneController,
keyboardType: TextInputType.phone,
autofocus: false,
style: new TextStyle(fontSize:14.0,
color: Colors.black,
fontWeight: FontWeight.w400,),
);
final checkBtn = RaisedButton(key: null, onPressed: check,
color: Colors.blue,
child: new Text("Check")
);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Country Code Demo'),
),
body: Center(
child: new ListView(
shrinkWrap: true,
padding: EdgeInsets.only(left: 24.0, right: 24.0),
children: <Widget>[
CountryCodePicker(
onChanged: _onCountryChange,
// Initial selection and favorite can be one of code ('IT') OR dial_code('+39')
initialSelection: 'IT',
favorite: ['+39','FR'],
// optional. Shows only country name and flag
showCountryOnly: false,
// optional. Shows only country name and flag when popup is closed.
showOnlyCountryWhenClosed: false,
// optional. aligns the flag and the Text left
alignLeft: false,
),
SizedBox(height: 16.0),
phone,
SizedBox(height: 16.0),
checkBtn
]
),
),
)
);
}
}

Related

How to get data in a Flutter-ListView?

I'm building a form for shipping and am able to add as many items as possible. (Adding a Widget in a ListView every time a button is pressed)
My question is, once the form widgets are created and filled, how do I get the information from each TextFormField in each Widget?
Once the information is retrieved I will send it to Firebase.
Here's the code I Have:
import 'package:flutter/material.dart';
import 'package:flutter_login_test/helpers/constants.dart';
class AddItemsToRequest extends StatefulWidget {
const AddItemsToRequest({Key? key}) : super(key: key);
#override
State<AddItemsToRequest> createState() => _AddItemsToRequestState();
}
class _AddItemsToRequestState extends State<AddItemsToRequest> {
List<TextEditingController> controllers = [];
List<Widget> fields = [];
RegExp regExp = RegExp('[aA-zZ]');
int quantity = 0;
double weight = 0;
double height = 0;
Widget itemForm() {
return Column(children: [
Container(
decoration:
BoxDecoration(color: grey, border: Border.all(color: black)),
width: double.infinity,
child: const Center(
child: Text('Package details',
style: TextStyle(
fontWeight: FontWeight.bold,
backgroundColor: grey,
fontSize: 24)),
)),
Row(
children: [
Flexible(
child: TextFormField(
onChanged: (value) {
quantity = value as int;
},
keyboardType: TextInputType.number,
validator: (value) => value!.isEmpty || value is int
? 'Quantity cannot be empty'
: null,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(
errorStyle: TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(
borderSide: BorderSide(),
borderRadius: BorderRadius.all(
Radius.circular(0.0),
),
),
fillColor: Color.fromARGB(255, 238, 238, 238),
filled: true,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent, width: 2.5),
),
hintText: "Quantity : "),
),
),
Flexible(
child: TextFormField(
onChanged: (value) {
weight = value as double;
},
keyboardType: TextInputType.number,
validator: (value) => value!.isEmpty || regExp.hasMatch(value)
? 'Weight cannot be empty'
: null,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(
errorStyle: TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(
borderSide: BorderSide(),
borderRadius: BorderRadius.all(
Radius.circular(0.0),
),
),
fillColor: Color.fromARGB(255, 238, 238, 238),
filled: true,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent, width: 2.5),
),
hintText: "Weight : "),
),
),
Flexible(
child: TextFormField(
onChanged: (value) {
height = value;
},
validator: (value) => value!.isEmpty ? 'Height cannot be empty' : null,
autovalidateMode: AutovalidateMode.onUserInteraction,
decoration: const InputDecoration(
errorStyle: TextStyle(color: Colors.redAccent),
border: OutlineInputBorder(
borderSide: BorderSide(),
borderRadius: BorderRadius.all(
Radius.circular(0.0),
),
),
fillColor: Color.fromARGB(255, 238, 238, 238),
filled: true,
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blueAccent, width: 2.5),
),
hintText: "Height : "),
),
),
],
),
]);
}
Widget _addTile() {
return ElevatedButton(
child: const Icon(Icons.add),
onPressed: () async {
final controller = TextEditingController();
final field = itemForm();
setState(() {
controllers.add(controller);
fields.add(field);
});
});
}
Widget _listView() {
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: fields.length,
itemBuilder: (context, index) {
final item = fields[index];
return Dismissible(
key: ObjectKey(item),
onDismissed: (direction) {
// Remove the item from the data source.
setState(() {
fields.removeAt(index);
});
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(content: Text('Package removed')));
},
background: Container(
color: const Color.fromARGB(255, 210, 31, 19),
child: const Center(
child: Text(
'Remove ',
style: TextStyle(
color: white, fontWeight: FontWeight.bold, fontSize: 32),
),
)),
child: Container(
width: double.infinity,
margin: const EdgeInsets.all(5),
child: fields[index],
),
);
},
);
}
Widget _okButton() {
return ElevatedButton(
onPressed: () {
for (var element in fields) {
print(quantity);
}
Navigator.of(context).pop();
print('ok');
},
child: const Text("OK"),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(backgroundColor: blue),
body: Column(
mainAxisSize: MainAxisSize.max,
children: [
Flexible(child: _addTile()),
SizedBox(
height: MediaQuery.of(context).size.height - 200,
child: _listView()),
Flexible(child: _okButton()),
],
),
);
}
}
I think you are expecting this answer. iterate your list of texteditingcontroller and get the text stored in that controllers one by one.
for (int i = 0; i < controllers.length; i++) {
var data = controllers[i].text;
//print or add data to any other list and insert to another list and save to database
}

raised button does not shows answer until I select a drop down item even after assigning a default value

I was making a simple S.I Calculator which has a field for principal amount intrest, and time along with that i have a dropdown to select the currency.
Problem is when I press 'calculate' RaisedButton(looking at the image might help) nothing appears on screen (Initially I thought there is problem with buttton but later ) I found out that after pressing RaisedButton if I selected any item from dropdown then answer appears why is this happening, I have set an inital value as _selected = 'Rupee' am I doing something wrong?.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Simple Intrest Calculator',
home: MyHomePage(),
theme: ThemeData(
brightness: Brightness.dark,
primaryColor: Colors.indigo,
accentColor: Colors.indigoAccent,
),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var _currencies = ['Rupee', 'Dollar', 'Pound'];
final _minPadding = 5.0;
var _selected = 'Rupee';
TextEditingController principalCntr = TextEditingController();
TextEditingController roiCntr = TextEditingController();
TextEditingController termCntr = TextEditingController();
String _amount = '0';
#override
Widget build(BuildContext context) {
TextStyle styles = Theme.of(context).textTheme.headline6;
return Scaffold(
//resizeToAvoidBottomPadding: false,
appBar: AppBar(
title: Text('S.I Calculator'),
centerTitle: true,
),
body: Container(
margin: EdgeInsets.symmetric(vertical: 0, horizontal: _minPadding * 2),
child: ListView(
children: [
getImg(),
Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: TextField(
controller: principalCntr,
keyboardType: TextInputType.number,
style: styles,
decoration: InputDecoration(
labelText: 'Principal',
hintText: 'Enter principal amount',
labelStyle: styles,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0),
),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: TextField(
controller: roiCntr,
keyboardType: TextInputType.number,
style: styles,
decoration: InputDecoration(
labelText: 'Intrest',
hintText: 'Enter intrest rate',
labelStyle: styles,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0),
),
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Expanded(
child: TextField(
controller: termCntr,
keyboardType: TextInputType.number,
style: styles,
decoration: InputDecoration(
labelText: 'Time',
hintText: 'Time in years',
labelStyle: styles,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5.0),
),
),
),
),
SizedBox(width: 50,),
Expanded(
child: DropdownButton(
value: _selected,
onChanged: (newVal) {
setState(() {
_selected = newVal;
});
},
items: _currencies.map((selectedVal) {
return DropdownMenuItem(
value: selectedVal,
child: Text(selectedVal),
);
}).toList(),
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Expanded(
child: RaisedButton(
color: Theme.of(context).accentColor,
textColor: Theme.of(context).primaryColor,
child: Text('Calculate'),
onPressed: (){
_amount = _calculateReturns();
},
),
),
SizedBox(width: 20),
Expanded(
child: RaisedButton(
color: Theme.of(context).primaryColorDark,
textColor: Theme.of(context).primaryColorLight,
child: Text('Clear', style: TextStyle(fontSize: 20,),),
onPressed: (){
debugPrint('pressed');
},
),
),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(_amount, style: styles,),
),
],
),
),
);
}
String _calculateReturns(){
double principal = double.parse(principalCntr.text);
double roi = double.parse(roiCntr.text);
double year = double.parse(termCntr.text);
double sI = principal + (principal*roi*year)/100;
String res = 'After $year years, you get $sI';
return res;
}
Widget getImg() {
AssetImage img = AssetImage('images/money.jpg');
Image image = Image(image: img, width: 125, height: 125);
return Container(
child: image,
margin: EdgeInsets.all(_minPadding * 10),
);
}
}
This is after i click Raised Button
This is after i select an item from dropdown but do not click on the button again:
Code walkthrough:
made a list of _currencies.
added textinput fields dropdown button and two raised buttons.
when calculate button is pressed _calculateReturns() is called which returns a value and stores it in _amount
Output is just a Text widget.
you forgot to update the screen when pressing on the button, remember every time you need to change the content of the page or update it you have to call the method :
setState(() {
// code here for values to be updated
});
so in your onPressed function of Raised button you have to add it like that :
onPressed: (){
_amount = _calculateReturns();
setState(() { });
}

Flutter: Password Check

I will enter the password to the user 2 times. but i don't know how to check this. How can I be sure that both passwords are spelled the same? can i do this?
here is my code,(I just put the relevant parts in order not to be long)
class _RegisterPageState extends State<RegisterPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
_paddingPasswordWidget('Password', 'Password'),
_paddingPasswordWidget('Password Again', 'Password Again'),
],
),
),
),
);
}
}
_paddingPasswordWidget(String hintTextStr, String labelTextStr) {
return Padding(
padding: EdgeInsets.only(top: 15, left: 22, right: 22),
child: TextFormField(
keyboardType: TextInputType.text,
style: TextStyle(
color: HexColor('#868686'),
),
decoration: CommonInputStyle.textFieldStyle(
hintTextStr: hintTextStr,
labelTextStr: labelTextStr,
),
obscureText: true,
),
);
}
class CommonInputStyle {
static InputDecoration textFieldStyle(
{String labelTextStr = "", String hintTextStr = ""}) {
return InputDecoration(
contentPadding: EdgeInsets.only(left: 20, top: 5, bottom: 5, right: 20),
labelText: labelTextStr,
hintText: hintTextStr,
labelStyle: TextStyle(fontSize: 14, color: HexColor('#868686')),
hintStyle: TextStyle(fontSize: 14, color: HexColor('#868686')),
filled: true,
fillColor: HexColor('#EEF2F4'),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(16),
borderSide: BorderSide.none,
),
);
}
}
You can try putting textEditingController in your fields, then you compare them. Something like this:
var textFieldPasswordController = TextEditingController();
var textFieldConfirmPasswordController = TextEditingController();
then you pass these as controllers in your TextFormField:
TextFormField(
controller: textFieldPasswordController //as an example
keyboardType: TextInputType.text,
style: TextStyle(
color: HexColor('#868686'),
),
Now you just need to check if textFieldPasswordController.text equals to textFieldConfirmPasswordController.text. You can check this in the onChange or validator function of TextFormField
if(textFieldPasswordController.text == textFieldConfirmPasswordController.text){
print("Access granted");
} else{
print("Try again");
}

How to use custom text field in another StatefulWidget class with a lot of parameters?

Today I made a custom text field of my own and I want to use it in many of the pages but it contains some arguments.
You can see here
import 'package:flutter/material.dart';
class RequiredText extends StatefulWidget {
#override
_RequiredTextState createState() => _RequiredTextState();
}
class _RequiredTextState extends State<RequiredText> {
final myController = TextEditingController();
#override
void dispose() {
myController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
String LabelTextField;
String HelperTextField;
Color ColorBorder;
Color ColorField;
Color ColorCursor;
return Padding(
padding: const EdgeInsets.only(left: 18.0),
child: TextField(
cursorColor: ColorCursor,
style: TextStyle(
color: ColorField,
),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.next,
controller: myController,
decoration: InputDecoration(
enabledBorder: new OutlineInputBorder(
borderSide: BorderSide(width: 1.5, color: ColorBorder)),
border: OutlineInputBorder(
borderSide: new BorderSide(color: Colors.cyan[200]),
borderRadius: new BorderRadius.all(Radius.circular(20.0))),
helperText: HelperTextField,
labelText: LabelTextField,
labelStyle: TextStyle(
color: Colors.black26,
fontSize: 20.0,
fontFamily: 'DancingScript',
),
icon: Icon(
Icons.apps,
)),
),
);
}
}
But I want to use this in my main.dart class and other pages too.
But it is showing errors
import 'package:AllInOneCalci/CustomTextFields.dart';
import 'package:AllInOneCalci/customAppBar.dart';
import 'package:flutter/material.dart';
class BMICalcUI extends StatefulWidget {
#override
_BMICalcUIState createState() => _BMICalcUIState();
}
class _BMICalcUIState extends State<BMICalcUI> {
#override
Widget build(BuildContext context) {
double AppBarHeight = MediaQuery.of(context).size.height;
return Scaffold(
appBar: customAppBar(
height: (AppBarHeight / 3) * 0.4,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(top: 18.0),
child: Text(
'All In One Cali',
style: TextStyle(
color: Colors.black,
fontSize: 35.0,
fontFamily: 'DancingScript',
fontWeight: FontWeight.bold),
),
),
],
),
),
body: Padding(
padding: const EdgeInsets.only(top: 18.0),
child: Container(
width: 300.0,
child: Column(
children: [
RequiredText('Height', 'Input height in meters', Colors.cyan[200],
Colors.redAccent, Colors.redAccent),
],
),
),
),
);
}
}
Also I want to use this in many of my pages. Can you help me that how can I do this?
It would be very helpful to me. I am Stuck here
RequiredText('Height', 'Input height in meters', Colors.cyan[200],
Colors.redAccent, Colors.redAccent),
This line is showing error.
String LabelTextField;
String HelperTextField;
Color ColorBorder;
Color ColorField;
Color ColorCursor;
you mentioned the param but you didn't initialize it ,
do it in this way
class RequiredText extends StatefulWidget {
String LabelTextField;
String HelperTextField;
Color ColorBorder;
Color ColorField;
Color ColorCursor;
RequiredText(this.LabelTextField,this.HelperTextField,this.ColorBorder,this.ColorField,this.ColorCursor);
#override
_RequiredTextState createState() => _RequiredTextState();
}
class _RequiredTextState extends State<RequiredText> {
final myController = TextEditingController();
#override
void dispose() {
myController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 18.0),
child: TextField(
cursorColor: widget.ColorCursor,
style: TextStyle(
color: widget.ColorField,
),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.next,
controller: myController,
decoration: InputDecoration(
enabledBorder: new OutlineInputBorder(
borderSide: BorderSide(width: 1.5, color: widget.ColorBorder)),
border: OutlineInputBorder(
borderSide: new BorderSide(color: Colors.cyan[200]),
borderRadius: new BorderRadius.all(Radius.circular(20.0))),
helperText: widget.HelperTextField,
labelText: widget.LabelTextField,
labelStyle: TextStyle(
color: Colors.black26,
fontSize: 20.0,
fontFamily: 'DancingScript',
),
icon: Icon(
Icons.apps,
)),
),
);
}
}

Flutter replace "," with "."

I have a TextField where I allow numbers like 1,4. I am trying ti replace the , to a . so the number will be 1.4.
I am trying this
double alphareceipe = double.parse(_alphareceipe.text);
alphareceipe = alphareceipe.replace("," ".");
But get this error:
error: The method 'replace' isn't defined for the class 'double'. (undefined_method at [brewingapp] lib/screens/calculator/alphaacid.dart:227).
The total code looks like this:
import 'package:flutter/material.dart';
import 'package:firebase_admob/firebase_admob.dart';
import 'package:brewingapp/app_localizations.dart';
import 'package:flutter/services.dart';
import 'package:devicelocale/devicelocale.dart';
const String testDevice = "Mobile_id";
class AlphaAcid extends StatefulWidget {
#override
_AlphaAcidState createState() => _AlphaAcidState();
}
class _AlphaAcidState extends State<AlphaAcid> {
}
String _emiResult = "";
final TextEditingController _weight = TextEditingController();
final TextEditingController _alphareceipe = TextEditingController();
final TextEditingController _alphanew = TextEditingController();
#override
void initState() {
initPlatformState();
super.initState();
}
#override
String _locale;
Future<void> initPlatformState() async {
String currentLocale;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
currentLocale = await Devicelocale.currentLocale;
print(currentLocale);
} on PlatformException {
print("Error obtaining current locale");
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_locale = currentLocale;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context).translate('Hopsalpha'),),
backgroundColor: Colors.green[800],
//elevation: 0.0,
),
body: Center(
child: Container(
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(20.0),
child: TextField(
cursorColor: Colors.green[800],
controller: _alphareceipe,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
),
filled: true,
fillColor: Colors.green[10],
labelText: _locale != 'da-DK'
? "Alpha acid receipe"
: "Alpha syre opskrift",
labelStyle: TextStyle(color: Colors.green[800])
),
keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: <TextInputFormatter>[
// WhitelistingTextInputFormatter.digitsOnly
],
),
),
Container(
padding: EdgeInsets.all(20.0),
child: TextField(
cursorColor: Colors.green[800],
controller: _alphanew,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
),
filled: true,
fillColor: Colors.green[10],
//labelText: "Final Gravity (1018)",
labelText: _locale != 'da-DK'
? "Your alpha acid"
: "Din alpha syre",
labelStyle: TextStyle(color: Colors.green[800]),
),
keyboardType: TextInputType.numberWithOptions(decimal: true),
inputFormatters: <TextInputFormatter>[
//WhitelistingTextInputFormatter.digitsOnly
],
),
),
Container(
padding: EdgeInsets.all(20.0),
child: TextField(
cursorColor: Colors.green[800],
controller: _weight,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
),
filled: true,
fillColor: Colors.green[10],
//labelText: "Final Gravity (1018)",
labelText: _locale != 'da-DK'
? "Weight receipe"
: "Vægt i opskrift",
labelStyle: TextStyle(color: Colors.green[800]),
),
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
WhitelistingTextInputFormatter.digitsOnly
],
),
),
Flexible(
fit: FlexFit.loose,
child: FlatButton(
onPressed: _handleCalculation,
//child: Text("Calculate"),
child: Text(AppLocalizations.of(context).translate('calculate'),),
color: Colors.green[600],
textColor: Colors.white,
padding: EdgeInsets.only(top: 10.0, bottom: 10.0, left: 24.0, right: 24.0),
),
),
emiResultsWidget(_emiResult)
],
),
),
));
}
void _handleCalculation() {
double newWeight = 0.0;
//
//
//
//
//
double alphareceipe = double.parse(_alphareceipe.text);
alphareceipe = alphareceipe.replace("," ".");
int alphanew =int.parse(_alphanew.text);
int weightreceipe = int.parse(_weight.text);
//
try {
newWeight = (weightreceipe * alphareceipe) / alphanew;
_emiResult = newWeight.toStringAsFixed(0);
setState(() {
});
} //catch(e) {
on Exception catch(e){
print(e);
setState(() {
});
}
//_emiResult = A.toStringAsFixed(1);
//setState(() {
//});
}
Widget emiResultsWidget(emiResult) {
bool canShow = false;
String _emiResult = emiResult;
if(_emiResult.length > 0) {
canShow = true;
}
return
Container(
margin: EdgeInsets.only(top: 30.0, left: 20.0, right: 20.0),
alignment: FractionalOffset.center,
color: Colors.green[50],
child: canShow ? Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
//crossAxisAlignment: CrossAxisAlignment.start,
//mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget> [
Padding(
padding: EdgeInsets.all(10.0),
child:
Text(AppLocalizations.of(context).translate('newweight'),
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.green[800],
),
)
),
SizedBox(width: 20.0,),
Text(_emiResult,
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.green[800],
)
),
SizedBox(width: 10.0,),
]),
]
) : Container(),
);
}
}
I would suggest to use an appropriate keyboard type in combination with an input formatter.
keyboardType: TextInputType.numberWithOptions(decimal: allowDecimal),
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(RegExp(r'[0-9]+[,.]{0,1}[0-9]*')),
TextInputFormatter.withFunction(
(oldValue, newValue) => newValue.copyWith(
text: newValue.text.replaceAll(',', '.'),
),
),
],
This way, the user can only enter digits and ",", ".", "-" and even if a "," is entered, the second input formatter (they can be chained) replaces the ",". All this happens while this is still a String and not a number.
You cannot use a String function on a double. Replace the symbol on the String, then cast to double.
You are trying to replace the characters after the text has already been converted to a double. Try this instead:
double alphareceipe = double.parse(_alphareceipe.text.replaceAll(",", "."));