'字符串类型不是 double 的子类型'

' type string is not a subtype of double'


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,
          )
        ],
      ),
    );
  }
}

我已经使用控制器从 pg1 中将数量作为字符串导入。 Text(total.toString()) 部分给出了 字符串不是 double 的子类型的错误。如何解决这个问题?

欢迎来到 SOF

你不是在解析,而是在转换!这迫使总数为 return a stringnull.

替换

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

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