[英]Stateless widget to stateful widget ( using Create state)
[錯誤][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');
}),
],
),
),
);
}
}
錯誤我正在 Udemy 進行課程,因為他們得到了相同代碼的 output 但對我來說它顯示這樣的錯誤 ** ** 小部件庫捕獲的異常** MyAppState#f6d27(生命周期 state:已創建,沒有小部件,未安裝)** [1]: https://i.stack.imgur.com/NFGhN.jpg
您需要創建一個私有 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(),
);}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.