Flutter StatefulWiget vs Statelesswidget

Flutter StatefulWiget vs Statelesswidget

當要使用StatefulWiget時,需要有兩個class,其一是繼承於StatefulWiget的class,另一個是繼承於State的class

在語法上有兩件事情要注意

  1. State 的class 繼承時記得指定屬於哪一個StatefulWiget
  2. StatefulWiget implement createState() function
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
// 2.implement createState
return MyAppState();
}

}

class MyAppState extends State<MyApp>{
// 1.繼承時,指定屬於哪一個StatefulWidget
var questionIndex = 0;
var questions = ["你喜歡貓嗎?", "你喜歡狗嗎?"];
answerTheQuestion(){
setState(() {
if(questionIndex == 0){
questionIndex += 1;
}else{
questionIndex = 0;
}
});

print("Button is pressed");
}

@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Hello World"),
),
body: Column(children: <Widget>[
Text(questions[questionIndex]),
RaisedButton(child: Text("喜歡"),onPressed: answerTheQuestion,),
RaisedButton(child: Text("不喜歡"),onPressed: answerTheQuestion),

],),
),
);
}
}

呈上,您可能有注意到setState這個function,這部分就是去告訴flutter需要重新繪製這個Wigets,但是這個setState不是重繪整個App的Wigets,只是在這個比較簡單的例子,我直接讓整個App 都是StatefulWidget,所以在這個範例上他是重繪整個App

你知道拍手不止可以拍一下嗎?若對您有幫助請幫我拍手哦^^