Problem With Refreshing Answer In Flutter Addition Calculator Problem

I was making a small addition calculator in flutter but do not know how to get the text showing the answer to refresh. I am currently a beginner trying to learn flutter and wanted to do this as a nice small project to extend my knowledge. I know at least that it has to be inside a stateful widget. Here is my current code:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: MyHomePage());
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Calculator"),
      ),
      body: TextFields(),
    );
  }
}

class TextFields extends StatefulWidget {
  @override
  _TextFieldsState createState() => _TextFieldsState();
}

class _TextFieldsState extends State<TextFields> {
  int num1 = 0;
  int num2 = 0;

  void assignNum1(value) {
    num1 = int.parse(value);
  }

  void assignNum2(value) {
    num2 = int.parse(value);
  }

  String ans() {
    return (num1 + num2).toString();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        TextField(
          decoration: InputDecoration(
            labelText: "Enter Your 1st number",
          ),
          onChanged: (value) => assignNum1(value),
        ),
        TextField(
          decoration: InputDecoration(
            labelText: "Enter Your 2nd number",
          ),
          onChanged: (value) => assignNum2(value),
        ),
        Text(ans())
      ]
    );
  }
}


Read more here: https://stackoverflow.com/questions/66266062/problem-with-refreshing-answer-in-flutter-addition-calculator-problem

Content Attribution

This content was originally published by Galaxy Fire at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: