我正在尝试在setState()中设置变量,但出现错误

时间:2019-04-30 13:40:19

标签: dart flutter

这是变量初始化

  var displayResult = '';

这里是印刷代码

 Padding(
                padding: EdgeInsets.all(5.0),
                child: Row(
                  children: <Widget>[
                    Expanded(
                        child: RaisedButton(
                            color: Theme
                                .of(context)
                                .primaryColor,
                            textColor: Theme
                                .of(context)
                                .primaryColorLight,
                            child: Text("calculate"),
                            onPressed: () {
                              setState(() {
                              this.displayResult = _calculateTotalReturn();
                              });
                            },
                        )),

我正在尝试调用的功能

  String _calculateTotalReturn() {
    setState(() {
      double principle = double.parse(principleController.text);
      double roi = double.parse(roiController.text);
      double term = double.parse(termController.text);
      double tap = principle + (principle * roi * term) / 100;
      String result = "After $term years, your investment will worth $tap $_currentItemSelected";
      return result;
    });
  }

这是我得到的错误

Performing hot reload...
Syncing files to device iPhone XR...
flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
flutter: The following assertion was thrown building SIForm(dirty, dependencies:
flutter: [_LocalizationsScope-[GlobalKey#4c1f9], _InheritedTheme], state: _SIFormState#b2966):
flutter: 'package:flutter/src/widgets/text.dart': Failed assertion: line 237 pos 15: 'data != null': is not
flutter: true.
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter:   https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #2      new Text (package:flutter/src/widgets/text.dart:237:15)
flutter: #3      _SIFormState.build (package:simple_cal/main.dart:153:24)
flutter: #4      StatefulElement.build (package:flutter/src/widgets/framework.dart:3825:27)
flutter: #5      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3736:15)
flutter: #6      Element.rebuild (package:flutter/src/widgets/framework.dart:3559:5)
flutter: #7      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2273:33)
flutter: #8      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:700:20)
flutter: #9      _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:268:5)
flutter: #10     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:988:15)
flutter: #11     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:928:9)
flutter: #12     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:749:7)
flutter: #14     _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)
flutter: #15     _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)
flutter: #16     _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
flutter: (elided 3 frames from class _AssertionError and package dart:async)
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
Reloaded 1 of 432 libraries in 641ms.

这是完整的main.dart文件

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

Widget MyApp() {
  return MaterialApp(
    title: 'Simple Intrest app',
    home: SIForm (),
    theme: ThemeData(
      primaryColor: Colors.deepPurple,
      accentColor: Colors.deepPurpleAccent
    ),
  );
}

class SIForm extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
      return _SIFormState ();
  }
}

class _SIFormState extends State<SIForm> {
  var _currencies = ["INR", "USD", "CAD"];

  var _currentItemSelected = "INR";

  var displayResult = '';

  TextEditingController principleController = TextEditingController();
  TextEditingController roiController = TextEditingController();
  TextEditingController termController = TextEditingController();


  @override
  Widget build(BuildContext context) {
    TextStyle textStyle = Theme
        .of(context)
        .textTheme
        .title;

    return Scaffold(

      appBar: AppBar(
        title: Text("Simple Interest Calc"),
      ),

      body: Container(padding: EdgeInsets.only(top: 50.0),
        child: ListView(
          children: <Widget>[
            Padding(
                padding: EdgeInsets.all(5.0),
                child: TextField(
                  keyboardType: TextInputType.number,
                  controller: principleController,
                  decoration: InputDecoration(
                      labelText: 'principle',
                      hintText: '0.00',
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5.0)
                      )
                  ),
                )),

            Padding(
                padding: EdgeInsets.all(5.0),
                child: TextField(
                  controller: roiController,
                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(
                      labelText: 'Rate of Interest',
                      hintText: '0.00',
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5.0)
                      )
                  ),
                )),

            Padding(
                padding: EdgeInsets.all(5.0),
                child: Row(
                  children: <Widget>[
                    Expanded(child: TextField(
                      controller: termController,
                      keyboardType: TextInputType.number,
                      decoration: InputDecoration(
                          labelText: 'Terms',
                          hintText: '%',
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(5.0)
                          )
                      ),
                    )),


                    Container(width: 10.0),
                    Expanded(
                      child: DropdownButton<String>(
                        items: _currencies.map((String value) {
                          return DropdownMenuItem<String>(
                            value: value,
                            child: Text(value),
                          );
                        }).toList(),
                        value: _currentItemSelected,
                        onChanged: (val) {
                          _ondropDownChange(val);
                        },),
                    ),
                  ],
                )),

            Padding(
                padding: EdgeInsets.all(5.0),
                child: Row(
                  children: <Widget>[
                    Expanded(
                        child: RaisedButton(
                            color: Theme
                                .of(context)
                                .primaryColor,
                            textColor: Theme
                                .of(context)
                                .primaryColorLight,
                            child: Text("calculate"),
                            onPressed: () {
                              setState(() {
                              this.displayResult = _calculateTotalReturn();
                              });
                            },
                        )),
                    Container(width: 5.0),
                    Expanded(
                        child: RaisedButton(
                            color: Theme
                                .of(context)
                                .accentColor,
                            textColor: Theme
                                .of(context)
                                .primaryColorLight,
                            child: Text("Reset"),
                            onPressed: () {
                              setState(() {
                             //   _reset();
                              });
                            }
                        )),
                  ],
                )),

            Padding(
                padding: EdgeInsets.all(5.0),
                child: Text(this.displayResult),
            )
          ],
        ),
      ),
    );
  }

  void _ondropDownChange(String value) {
    setState(() {
      this._currentItemSelected = value;
    });
  }

  String _calculateTotalReturn() {
    setState(() {
      double principle = double.parse(principleController.text);
      double roi = double.parse(roiController.text);
      double term = double.parse(termController.text);
      double tap = principle + (principle * roi * term) / 100;
      String result = "After $term years, your investment will worth $tap $_currentItemSelected";
      return result;
    });
  }

  void _reset() {
    setState(() {
      this.principleController.text = " ";
      this.roiController.text = " ";
      this.termController.text = " ";
      this.displayResult = " ";
    });
  }
}

1 个答案:

答案 0 :(得分:1)

您应该摆脱setState中的_calculateTotalReturn。您提供给return result;的内联函数返回了setState,而_calculateTotalReturn实际上返回了null