Flutter Need for StatefulWidget

Continuing from our last blog post “Flutter/Dart Anonymous Function” , in this post we have added a list of questions in build() for now, with only two questions.

 var questions = [
      'What\'s your favorite color?',
      'What\'s your favorite animal?'
    ];

We have introduced a variable ‘questionIndex’ to keep track and change the question on the go. We increment this variable questionIndex in answerQuestion() function in MyApp class.

var questionIndex = 0;

  void answerQuestion() {
    questionIndex++;
    print(questionIndex);
    //print('Answer chosen!');
  }

Instead of display a static question in the Text() widget, we now display a question from questions list using questionIndex.

Text(questions[questionIndex]

Here is the full application code snippet.

//File Name: main.dart
import 'package:flutter/material.dart';

/*
* The arrow function allows us to create a simplified function consisting of a single expression.
* We can omit the curly brackets and the return keyword
*/

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

class MyApp extends StatelessWidget {
  var questionIndex = 0;

  void answerQuestion() {
    questionIndex++;
    print(questionIndex);
    //print('Answer chosen!');
  }

  @override
  Widget build(BuildContext context) {
    var questions = [
      'What\'s your favorite color?',
      'What\'s your favorite animal?'
    ];
    return MaterialApp(
      /*
      * A Scaffold Widget provides a framework which implements the basic material design visual
      * layout structure of the flutter app.
       */
      home: Scaffold(
        appBar: AppBar(
          title: Text('First Flutter App'),
        ),
        body: Column(
          children: <Widget>[
            Text(questions[questionIndex]),
            ElevatedButton(
              child: Text('Answer1'),
              //onPressed takes a function
              onPressed: answerQuestion,
            ),
            ElevatedButton(
              child: Text('Answer2'),
              onPressed: () => print('Answer2 chosen!'),
            ),
            ElevatedButton(
              child: Text('Answer3'),
              onPressed: () {
                //...multiline function body
                print('Answer3 chosen');
              },
            ),
          ],
        ),
      ),
    );
  } //build()
} //MyApp()

Output

Output

What happens if we first Answer1 button? The question should change, right? but it doesn’t change because we are trying to change the internal state of the widget.

Remember, we can’t manage the state of a StatelessWidget, for that we need StatefulWidget which we’ll cover in next blog post.

Comments

comments

no responses for Flutter Need for StatefulWidget

    Leave a Reply

    Your email address will not be published. Required fields are marked *