onPressed-如何执行功能然后检索答案

时间:2018-12-14 19:20:06

标签: flutter

我试图在按下按钮时执行一些简单的计算。计算结果位于另一个类中。我在执行计算然后检索结果时遇到麻烦。我尝试了(),()=>,没有括号,setState等的几种不同组合。初学者。

class TestPage extends StatefulWidget {
  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {

  double variableToShow = RpdCalculations(30, 50).abRPDvalue;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        body: Column(
      children: <Widget>[
        SizedBox(
          height: 150,
        ),
        Text('This is where the variables will be displayed'),
        Text('${RpdCalculations(30, 50).abRPDvalue} abRPD'),
        Text('${RpdCalculations(30, 50).arpv} arpv'),
        RaisedButton(
            onPressed: () => RpdCalculations(30, 50).allRPDcalcs
            //onPressed: () => setState(() {RpdCalculations(30, 50).allRPDcalcs();})
        ),
      ],
    ));
  }
}

class RpdCalculations {
  double arpv = 0;
  double brpv = 0;
  double abRPDvalue = 4;

  RpdCalculations(this.arpv, this.brpv);

  allRPDcalcs() {
    return abRPDvalue = calcRPD(arpv, brpv);
  }

  calcRPD(double x, double y) {
    if (x > y) {
      return x - y;
    } else {
      return y - x;
    }
  }
}

1 个答案:

答案 0 :(得分:0)

我认为需要对计算类进行重构。从外部计算arpvbrpv值时似乎没有用。

在不完全知道您的真实意图的情况下,您可以尝试以下操作:

class TestPage extends StatefulWidget {
  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  RpdCalculations calc;

  @override
  void initState() {
    super.initState();
    calc = RpdCalculations()..allRPDcalcs(30, 50);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text('This is where the variables will be displayed'),
            Text('${calc.abRPDvalue} abRPD'),
            RaisedButton(
              onPressed: () => setState(() {
                    calc.allRPDcalcs(40, 10);
                  }),
            ),
          ],
        ),
      ),
    );
  }
}

class RpdCalculations {
  double abRPDvalue = 4;

  RpdCalculations();

  allRPDcalcs(double arpv, double brpv) {
    abRPDvalue = calcRPD(arpv, brpv);
  }

  calcRPD(double x, double y) {
    if (x > y) {
      return x - y;
    } else {
      return y - x;
    }
  }
}