Search code examples
mathflutterformulapercentagediscount

calculate discount of prices in flutter


I want to try define below formula to calculate between old price and new price and show it on text widget but when i want to use it in an double variable i've got this error : "Only static members can be accessed in initializers" and this is what i want to do:

class ProductDetails extends StatefulWidget {
 final prod_fullName;
 final prod_pic;
 final prod_old_price;
 final prod_price;
 double percent=(prod_old_price - prod_price)/prod_old_price*100;
ProductDetails({
 this.prod_fullName,
 this.prod_pic,
 this.prod_old_price,
 this.prod_price,
});

@override
_ProductDetailsState createState() => _ProductDetailsState();
}
class _ProductDetailsState extends State<ProductDetails> {
 Row{
  child:new Text("$percent%");
}

Solution

  • class ProductDetails extends StatefulWidget {
      final String prod_fullName;
      final String prod_pic;
      final double prod_old_price;
      final double prod_price;
    
      const ProductDetails({Key key, this.prod_fullName, this.prod_pic, this.prod_old_price, this.prod_price}) : super(key: key);
    
      @override
      _ProductDetailsState createState() => _ProductDetailsState();
    }
    class _ProductDetailsState extends State<ProductDetails> {
      double percent;
      @override
      void initState() {
        percent=(widget.prod_old_price - widget.prod_price)/widget.prod_old_price*100;
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        return Text("$percent%");
      }
    }