Search code examples
visual-studioflutterwidgetthrowstateful

UnimplementedError (FLUTTER)


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,
            )
          ],
        ),
      ),
    );
  }
}

Solution

  • 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();