' type string is not a subtype of double'

Issue


class Pg2 extends StatelessWidget {
  String amount;
  final a = TextEditingController();
  Pg2(this.amount);
  double get total {
    double amt = (amount as double);
    double p = (a.text as double);
    return (amt + (p / 100) * amt);
  }
  

  @override
  Widget build(BuildContext context) {
    void dialogbox() {
      showDialog(
          context: context,
          builder: (context) => AlertDialog(
                title: Text('You have to pay :'),
                content: Container(
                  child: Text(total.toString()),
                ),
              ));
    }

    return Scaffold(
      body: Column(
        children: [
          Text(amount.toString()),
          TextField(
            decoration:
                InputDecoration(labelText: 'Percent tip you want to give'),
            controller: a,
          ),
          RaisedButton(
            child: Text('Submit'),
            onPressed: dialogbox,
          )
        ],
      ),
    );
  }
}

I have imported amount from pg1 as string using controller. The part Text(total.toString()) is giving the
error that string is not a subtype of double. How to resolve this issue?

Solution

Welcome to SOF

You are not parsing, but casting! This forces total to either return a string or a null.

Replace

double get total {
    double amt = (amount as double);
    double p = (a.text as double);
    return (amt + (p / 100) * amt);
  }

with

double get total {
    double amt = double.parse(amount);
    double p = double.parse(a.text);
    return (amt + (p / 100) * amt);
  }

Answered By – AVEbrahimi

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *