Search code examples
buttonflutterreturntextfieldeventhandler

return a colored box after button pressed


I'm trying to learn flutter and right now I'm working on buttonclicks.

I have a very easy program below where the integer sum = 5. If the user returns 5 in the textfield and clicks the submit-button my goal is to return a green square below the submit button. If the user prints anything else, the square will be red.

I have actually no idea where to start with this more then I have in my code, so any help that puts me in the right direction is very appreciated. Thank you.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'buttonclicks',
      theme: ThemeData(primarySwatch: Colors.deepOrange),
      home: FirstClass(),
    );
  }
}

class FirstClass extends StatefulWidget {
  @override
  _FirstClassState createState() => _FirstClassState();
}

class _FirstClassState extends State<FirstClass> {
  int sum = 5;
  String enterAnswer;

  void handleCorrect() {
    setState(() {
      Container(
        height: 60.0,
        width: 70.0,
        decoration: BoxDecoration(color: Colors.green),
        child: Text('CORRECT'),
      );
    });
  }

  void handleFalse() {
    setState(() {
      Container(
        height: 60.0,
        width: 70.0,
        decoration: BoxDecoration(color: Colors.red),
        child: Text('FALSE'),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BUTTON-CLICKS'),
      ),
      body: Container(
        child: Center(
          child: Column(
            children: <Widget>[
              Container(
                width: 50.0,
                child: TextField(
                  textAlign: TextAlign.center,
                  autofocus: true,
                  keyboardType: TextInputType.number,
                  onChanged: (val) {
                    enterAnswer = val;
                  },
                ),
              ),
              RaisedButton(
                  child: Text('SUBMIT'),
                  onPressed: () {
                    if (enterAnswer.isNotEmpty) {
                      if (enterAnswer == sum) {
                        handleCorrect();   //setState
                      } else {
                        handleFalse();    //setState
                      }
                    }
                  }),
              Container(
                //handleCorrect or handleFalse
                child: Text("RETURN A GREEN OR A RED BOX"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Solution

  • How about something like the following. You should call setState when the button gets clicked and set some state to determine which color to show.

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'buttonclicks',
          theme: ThemeData(primarySwatch: Colors.deepOrange),
          home: FirstClass(),
        );
      }
    }
    
    class FirstClass extends StatefulWidget {
      @override
      _FirstClassState createState() => _FirstClassState();
    }
    
    class _FirstClassState extends State<FirstClass> {
      int sum = 5;
      String enterAnswer;
      Color containerColor;
    
      void setColorForAnswer()
      {
        setState(() {
         containerColor = enterAnswer != null && enterAnswer.isNotEmpty
                        ? (int.parse(enterAnswer) == sum
                            ? Colors.green
                            : Colors.red)
                        : Colors.transparent; 
        });
      }
    
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('BUTTON-CLICKS'),
          ),
          body: Container(
            child: Center(
              child: Column(
                children: <Widget>[
                  Container(
                    width: 50.0,
                    child: TextField(
                      textAlign: TextAlign.center,
                      autofocus: true,
                      keyboardType: TextInputType.number,
                      onChanged: (val) {
                        enterAnswer = val;
                      },
                    ),
                  ),
                  RaisedButton(
                      child: Text('SUBMIT'),
                      onPressed: () {
                        setColorForAnswer();
                      }),
                  Container(
                    width: 50,
                    height: 50,
                    color: containerColor,
                  ),
                ],
              ),
            ),
          ),
        );
      }
    }