Arun Prasath
Arun Prasath

Reputation: 1

Stateless widget to stateful widget ( using Create state)

[error][1]

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

  void answerQuestion() {
    setState(() {
      questionIndex = questionIndex + 1;
    });
    print(questionIndex);
  }
  @override
  Widget build(BuildContext context) {
    var question = [
      'what\'s your favorite colour?',
      'what\'s your favorite sports?',
    ];
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My app'),
        ),
        body: Column(
          children: [
            Text(question[questionIndex]),
            RaisedButton(
              child: Text('answer1'),
              onPressed: () => print('answer2'),
            ),
            RaisedButton(
              child: Text('answer2'),
              onPressed: () => print('answer2'),
            ),
            RaisedButton(
                child: Text('answer3'),
                onPressed: () {
                  print('answer3');
                }),
          ],
        ),
      ),
    );
  }
}

error I'm on going course in Udemy in that they got the output for the same code but for me it showing error like this ** ** Exception caught by widgets library ** MyAppState#f6d27(lifecycle state: created, no widget, not mounted)** [1]: https://i.sstatic.net/NFGhN.jpg

Upvotes: 0

Views: 110

Answers (1)

Rohit Chaurasiya
Rohit Chaurasiya

Reputation: 607

You need to create a private class.

class FilmList extends StatefulWidget {
  const FilmList({Key? key}) : super(key: key);

  @override
  _FilmListState createState() => _FilmListState();//need to add
}

class _FilmListState extends State<FilmList> {
  MovieQuery query = MovieQuery.year;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
child:Container(),
);}
}

Upvotes: 1

Related Questions