Pannam T
Pannam T

Reputation: 479

String to double conversion and vice versa throws null error

I am getting an error here below, I am using a string to convert double to 2 decimal places then reconverting the string to a double so I can divide it by 2 . I have to then convert it back to a string to use it in a text, Here, is the stripped out code plus the error, could you please take a look?

class _MainScreenState extends State<MainScreen> {
String price = "" ;

//using it in a function

 Future showMap(bool checkValue) async {
///
 setState(() {
        price =
            (roadInformation.distance * 39 + 50).toStringAsFixed(2);
         });

// using it in a text in the widget
 @override
  Widget build(BuildContext context) {
///
 Text(
    "Bhat ${(double.tryParse(price)/2).toString()}",
    style: TextStyle(
        fontSize: 18.0, fontFamily: "Brand Bold"),
)
}
 
}

The error doesn't occur when

Text(
    price,
    style: TextStyle(
        fontSize: 18.0, fontFamily: "Brand Bold"),
)

The error when dividing

I/flutter (21034): NoSuchMethodError: The method '/' was called on null.
I/flutter (21034): Receiver: null
I/flutter (21034): Tried calling: /()

Upvotes: 1

Views: 751

Answers (2)

Pannam T
Pannam T

Reputation: 479

Thank you guys, a simple empty/null check was required and Apologies if my question was not well put forward.

Text(
    (price == "") ?
    price :
    (double.tryParse(price) / 2).toString(),
    style: TextStyle(
        fontSize: 18.0, fontFamily: "Brand Bold"),
)

Upvotes: 1

Abbasihsn
Abbasihsn

Reputation: 2171

I think you have not called showMap! as a result, you try to parse empty string! provide a valid first value like String price = "" ; or call your function in initState or didChangeDependencies().

Upvotes: 2

Related Questions