【问题标题】:' type string is not a subtype of double''类型字符串不是双精度的子类型'
【发布时间】:2021-06-20 19:28:41
【问题描述】:

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()) 给出 字符串不是双精度子类型的错误。如何解决这个问题?

【问题讨论】:

    标签: flutter dart flutter-layout flutter-dependencies flutter-web


    【解决方案1】:

    欢迎来到 SOF

    你不是在解析,而是在转换!这会强制总返回 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);
      }
    

    【讨论】:

    • 感谢您的回复!你能告诉我解析和强制转换有什么区别吗?
    • 强制转换是它们兼容的类型转换,例如,将一个盒子强制转换为一个对象。但是解析是读取一个字符串并将其值评估为数字。
    猜你喜欢
    • 2019-10-08
    • 2013-05-18
    • 2015-12-04
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多