Search code examples
variablestextflutteroutputtextfield

Use textfield input to get a value output


I have made a simple textfield with a number keyboard. The user is to put in a number (to make it simple I have set the number to sum=5).

If input is = sum, the text 'correct answer' will be printed on the screen. If the user input !=sum, the returned text will be 'wrong answer'.

To test if I actually got the numbers right I have a testprint, which functions correct.

My problem is how to transform this print output to text (so that it will show as text in the app).

I have been thinking about validating and form, but since I actually already get the correct answer printed, it shows I already get the values correct. Right?

I have tried a ton of things, but nothing has worked so far, so any help is appreciated. Thank you.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Textfields2',
      home: MyHomeScreen(),
    );
  }
}

class MyHomeScreen extends StatefulWidget {
  @override
  _MyHomeScreenState createState() => _MyHomeScreenState();
}

class _MyHomeScreenState extends State<MyHomeScreen> {
  final int sum = 5;
  String output;
  String enterAnswer;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            TextField(
              textAlign: TextAlign.center,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(hintText: '?'),
              onChanged: (val) {
                enterAnswer = val;
              },
            ),
            RaisedButton(
                child: Text('Submit Answer'),
                onPressed: () {
                  if (enterAnswer.isNotEmpty) {
                    if (enterAnswer == sum.toString()) {
                      print('Correct'); //INTO TEXT
                    } else {
                      print('Wrong Answer');//INTO TEXT
                    }
                  }
                })
          ],
        ),
      ),
    );
  }
}

Solution

  • Below the RaisedButton add a Text Widget. It should look something like this:

    Text(output)
    

    , then replace the print() statement with a setState() function updating the output:

    setState(() {output = 'Correct';});
    

    To not get an error in the first place you have to initialize the output variable, so instead of only writing

    String output;
    

    write

    String output = "";