I have a text field that inputs a number and want to set that value equal to a double, but whenever I try it does nothing and I am not sure why.
Below is how the textfield is implemented
TextField(
keyboardType: TextInputType.number,
controller: _incomeController,
style: const TextStyle(
color: Colors.black,
),
decoration: const InputDecoration(
filled: true,
fillColor: Colors.white,
hintText: 'Ba开发者_运维百科lance',
hintStyle: TextStyle(color: Colors.grey),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
),
borderSide: BorderSide.none,
),
),
),
This is how I am trying to convert the text field to the double income.
income = _incomeController.text.trim() as double;
First seem like you are using wrong controller :
_balanceController
instead of _incomeController
Second, you cannot cast string to double like that, instead try this:
income = double.tryParse(_balanceController.text.trim());
You must set TextField controller same. You are trying to get text from other TextEditingController. If you declared income nullable like that:
double? income;
You can convert to String like that:
income = double.tryParse(_balanceController.text.trim());
print(income is double);
And if text can't be converted to double then you get null, so print(income is double);
will print false;
I created sample flutter application. Here you can see the whole code:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatefulWidget {
const MyWidget({Key? key});
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
final _balanceController = TextEditingController();
double? result;
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text("Result: $result"),
TextField(
keyboardType: TextInputType.number,
controller: _balanceController,
style: const TextStyle(
color: Colors.black,
),
decoration: const InputDecoration(
filled: true,
fillColor: Colors.white,
hintText: 'Balance',
hintStyle: TextStyle(color: Colors.grey),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
),
borderSide: BorderSide.none,
),
),
),
OutlinedButton(
onPressed: () {
setState(() {
result = double.tryParse(_balanceController.text.trim());
print(result is double);
});
},
child: const Text("Show result"),
),
],
);
}
}
精彩评论