8

I'm super new at coding with Flutter and following this course that let's me create stateful widget. The problem is when I do, I get this throw UnimplementedError(); It should return to null. I have no clue what I'm doing wrong.

my code:

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    throw UnimplementedError();
  }
}
class MyAppState extends State<MyApp> {
  var questionIndex = 0;

  void answerQuestion() {
    setState(() {
      questionIndex = questionIndex + 1;
    });
    print(questionIndex);
  }

  @override
  Widget build(BuildContext context) {
    var questions = [
      "What's your favourite color?",
      "What's your favourite animal?",
    ];
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(
            "My First App",
          ),
        ),
        body: Column(
          children: [
            Text(
              questions[questionIndex],
            ),
            RaisedButton(
              child: Text("Answer 1"),
              onPressed: answerQuestion,
            ),
            RaisedButton(
              child: Text("Answer 2"),
              onPressed: answerQuestion,
            ),
            RaisedButton(
              child: Text("Answer 3"),
              onPressed: answerQuestion,
            )
          ],
        ),
      ),
    );
  }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Soun
  • 83
  • 1
  • 1
  • 3
  • 1
    You're getting UnimplementedError error because you're throwing the exception inside createState. – Bagata Dec 30 '20 at 14:28

1 Answers1

12

The createState() method includes a TODO comment:

@override
State<StatefulWidget> createState() {
  // TODO: implement createState
  throw UnimplementedError();
}

This comment is a kind reminder that we have something left to do.

However, the throw UnimplementedError() makes the reminder less friendly, forcing us to complete our TODO task and remove the UnimplementedError() line to make it work:

MyAppState createState() => MyAppState();
Stefano Amorelli
  • 4,553
  • 3
  • 14
  • 30