mocart
mocart

Reputation: 615

Can't setState in flutter

I try to setState in flutter (to change questions) on my test QUIZ app (im learning now). But when i click a button next, question on display is not change. But if i set var value manually, for ex 4, it displays on screen. I use _questionIndex var and add increment when user click next button, can anybody helps me please?


import 'package:flutter/material.dart';
import 'package:quiz/models/Questions.dart';
import 'package:quiz/widgets/answer.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final QuestionData data = QuestionData();

  Widget build(BuildContext context) {
    int _countResult = 0;
    int _questionIndex = 2;
    return Scaffold(
      appBar: AppBar(title: Text('QUIZ')),
      body: Container(
        constraints: BoxConstraints.expand(),
        decoration: BoxDecoration(
          color: const Color(0xff2a375a),
          image: DecorationImage(
            image: AssetImage('assets/images/bg.png'),
            fit: BoxFit.cover,
          ),),
        child: Column(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.all(10.0),
              child: Text(data.questions[_questionIndex].title,
                  style: Theme
                      .of(context)
                      .textTheme
                      .caption),
            ),
            ...data.questions[_questionIndex].answers
                .map((value) =>
                Answer(
                  title: value['answer'],
                ),)
                .toList(),
            RaisedButton(
              onPressed: () =>
                  setState(() {
                    _questionIndex = _questionIndex += 1;
                  }),
              child: Text('Next ' '$_questionIndex'),
            ),
          ],
        ),
      ),);
  }
}

Upvotes: 1

Views: 5632

Answers (2)

Programmer_3
Programmer_3

Reputation: 530

Question is not changing dynamically Because you place _countResult and _questionIndex inside of widget Method.Try to place these variables outside of widget method. When every time setState() is called it rerun build method.

Upvotes: 3

NiklasLehnfeld
NiklasLehnfeld

Reputation: 1080

  1. The problem is you declaration of the _questionIndex. You are declaring it as a local variable in the build function. This is why it is declared freshly every time you call setState(), since setState() calls again the build function.

    But what you want to do is saving the _questionIndex as well as _countResult as a member variable of your State. So it is declared independently of your build() function.

  2. The second thing:

_questionIndex += 1;

is equal to

_questionIndex = questionIndex + 1;

So this is one statement too much:

_questionIndex = questionIndex += 1;

My code suggestion would look like:


import 'package:flutter/material.dart';
import 'package:quiz/models/Questions.dart';
import 'package:quiz/widgets/answer.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final QuestionData data = QuestionData();
  int _countResult = 0;
  int _questionIndex = 2;

  Widget build(BuildContext context) {
    
    return Scaffold(
      appBar: AppBar(title: Text('QUIZ')),
      body: Container(
        constraints: BoxConstraints.expand(),
        decoration: BoxDecoration(
          color: const Color(0xff2a375a),
          image: DecorationImage(
            image: AssetImage('assets/images/bg.png'),
            fit: BoxFit.cover,
          ),),
        child: Column(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.all(10.0),
              child: Text(data.questions[_questionIndex].title,
                  style: Theme
                      .of(context)
                      .textTheme
                      .caption),
            ),
            ...data.questions[_questionIndex].answers
                .map((value) =>
                Answer(
                  title: value['answer'],
                ),)
                .toList(),
            RaisedButton(
              onPressed: () =>
                  setState(() {
                    _questionIndex += 1;
                  }),
              child: Text('Next ' '$_questionIndex'),
            ),
          ],
        ),
      ),);
  }
}

Upvotes: 3

Related Questions