J.W
J.W

Reputation: 1205

change containerColor from a list

I have previously asked a question regarding lists in Flutter. I got good help but new problems arose within the same list. Since this new probelm is of other character then the initial question I made this new question.

I have a list (the code below is simplified from my working-code to make my problem clearer) of blue colored containers.

When the user types in 5 and press the 'submit'-button the color of the first container should change to green (if not 5 the button should turn red). The second time the user press the 'submit'-button the second container should change color. And so on...

The problem I'm facing is that I can't get my increment to the list to work.

      import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'listing 4',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: FirstScreen(),
    );
  }
}

class FirstScreen extends StatefulWidget {
  @override
  _FirstScreenState createState() => _FirstScreenState();
}

class _FirstScreenState extends State<FirstScreen> {
  int sum = 5;
  String userAnswer;
  String correction = "";
  var _controller = new TextEditingController();
  int _counter = 1;

  List<Color> colors = [Colors.blue, Colors.blue, Colors.blue];

  submitPressed(int index) {
    if (userAnswer == sum.toString()) {
      setState(() {
        correction = sum.toString();
        colors[index] = Colors.green;
      });
    } else {
      setState(() {
        correction = sum.toString();
        colors[index] = Colors.red;
      });
    }
  }

  Widget myTextField() {
    return Container(
      width: 50.0,
      child: TextField(
        controller: _controller,
        textAlign: TextAlign.center,
        autofocus: true,
        keyboardType: TextInputType.number,
        onChanged: (val) {
          userAnswer = val;
        },
      ),
    );
  }

  Widget myListBuilder() {
    return Container(
      height: 50.0,
      width: 300.0,
      child: Padding(
        padding: const EdgeInsets.all(10.0),
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: 3,
          itemBuilder: buildContainer,
        ),
      ),
    );
  }

  Widget buildContainer(BuildContext context, int index) {
    return Container(
        child: Padding(
      padding: const EdgeInsets.only(top: 10.0),
      child: Container(
        height: 20.0,
        width: 15.0,
        decoration: BoxDecoration(
            color: colors[index], //this is the important line
            borderRadius: BorderRadius.all(Radius.circular(8.0))),
      ),
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Listing 4'),
      ),
      body: Container(
        child: Center(
           child: Column(
            children: <Widget>[
              Padding(
               padding: EdgeInsets.only(top: 10.0),
               child: Text('Correct answer is 5',
                    style: TextStyle(fontSize: 20.0)),
              ),
              myTextField(),
              RaisedButton(
                child: Text('Submit'),
                onPressed: () {
                  setState(() {
                    submitPressed(0);  //This will naturally only give index 0
                  });
                },
              ),
              myListBuilder(),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  buildContainer(context, 0),
                  buildContainer(context, 1),
                  buildContainer(context, 2)
                ],
              ),
              RaisedButton(
                child: Text('Next'),
                onPressed: () {
                  _counter++;
                  _controller.clear();
                  myTextField();
                },
              ),
              Text('This should be container no: $_counter'),
            ],
          ),
        ),
      ),
    );
  }
}

Upvotes: 0

Views: 58

Answers (1)

giggiogol
giggiogol

Reputation: 36

I can't figure out why you have this

submitPressed(0);

This code works:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'listing 4',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: FirstScreen(),
    );
  }
}

class FirstScreen extends StatefulWidget {
  @override
  _FirstScreenState createState() => _FirstScreenState();
}

class _FirstScreenState extends State<FirstScreen> {
  int sum = 5;
  String userAnswer;
  String correction = "";
  var _controller = new TextEditingController();
  int _counter = 0;

  List<Color> colors = [Colors.blue, Colors.blue, Colors.blue];

  submitPressed(int index) {
    if (userAnswer == sum.toString()) {
      setState(() {
        correction = sum.toString();
        colors[index] = Colors.green;
      });
    } else {
      setState(() {
        correction = sum.toString();
        colors[index] = Colors.red;
      });
    }
  }

  Widget myTextField() {
    return Container(
      width: 50.0,
      child: TextField(
        controller: _controller,
        textAlign: TextAlign.center,
        autofocus: true,
        keyboardType: TextInputType.number,
        onChanged: (val) {
          userAnswer = val;
        },
      ),
    );
  }

  Widget myListBuilder() {
    return Container(
      height: 50.0,
      width: 300.0,
      child: Padding(
        padding: const EdgeInsets.all(10.0),
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: 3,
          itemBuilder: buildContainer,
        ),
      ),
    );
  }

  Widget buildContainer(BuildContext context, int index) {
    return Container(
        child: Padding(
          padding: const EdgeInsets.only(top: 10.0),
          child: Container(
            height: 20.0,
            width: 15.0,
            decoration: BoxDecoration(
                color: colors[index], //this is the important line
                borderRadius: BorderRadius.all(Radius.circular(8.0))),
          ),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Listing 4'),
      ),
      body: Container(
        child: Center(
          child: Column(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(top: 10.0),
                child: Text('Correct answer is 5',
                    style: TextStyle(fontSize: 20.0)),
              ),
              myTextField(),
              RaisedButton(
                child: Text('Submit'),
                onPressed: () {
                  setState(() {
                    submitPressed(_counter);
                  });
                },
              ),
              myListBuilder(),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  buildContainer(context, 0),
                  buildContainer(context, 1),
                  buildContainer(context, 2)
                ],
              ),
              RaisedButton(
                child: Text('Next'),
                onPressed: () {
                  setState(() {
                    _counter++;
                  });
                  _controller.clear();
                  myTextField();
                },
              ),
              Text('This should be container no: ${_counter +1}'),
            ],
          ),
        ),
      ),
    );
  }
}

I changed the _counter to act like an index and use it as the parameter of the method submitPressed. I also put the increment in a setState, or you saw the new number only after hitting the Submit button.

Upvotes: 1

Related Questions