1. 程式人生 > 實用技巧 >重學flutter第三天下-StatefulWidget的使用(未完待續)

重學flutter第三天下-StatefulWidget的使用(未完待續)

上篇文章介紹了StatelessWidget的使用,這篇文章介紹一下StatefulWidget的使用,類似React的有狀態的元件,使用StatefulWidget元件分為兩步:

1、宣告的元件繼承StatefulWidget,過載 createState函式,返回State資料型別泛型為StatefulWidget,createState函式內部返回state元件。

2、生命State元件繼承State泛型為MyApp,這個State元件才是真正的元件,內部可以定義方法,屬性,過載build函式,並繫結方法。

程式碼如下:

 1 import 'package:flutter/material.dart';
2 3 void main() => runApp(MyApp("Hello World")); 4 5 class MyApp extends StatefulWidget { 6 // This widget is the root of your application. 7 8 String content; 9 10 MyApp(this.content); 11 12 @override 13 State<StatefulWidget> createState() { 14 // TODO: implement createState
15 return MyAppState(); 16 } 17 } 18 19 class MyAppState extends State<MyApp> { 20 21 bool isShowText =true; 22 23 void increment(){ 24 setState(() { 25 widget.content += "d"; 26 }); 27 } 28 29 @override 30 Widget build(BuildContext context) { 31 return MaterialApp(
32 title: 'Flutter Demo', 33 theme: ThemeData( 34 primarySwatch: Colors.blue, 35 ), 36 home: Scaffold( 37 appBar: AppBar(title: Text("Widget -- StatefulWidget及State"),), 38 body: Center( 39 child: GestureDetector( 40 child: isShowText? Text(widget.content) :null, 41 onTap: increment, 42 ) 43 ), 44 ) 45 ); 46 } 47 }

觀察程式碼MyApp元件內部只是定義了state即content,並重載了createState,createState內部返回了MyAppState。

而MyAppState元件繼承了State,State的泛型為MyApp,內部過載了build。

MyApp和MyAppState犬牙交錯,互相咬合構成了StatefulWidget,MyApp的createState返回MyAppState,MyAppState繼承泛型為MyApp的state。

MyApp的簡化程式碼如下:

 1 class MyApp extends StatefulWidget {
 2   // This widget is the root of your application.
 3 
 4   @override
 5   State<StatefulWidget> createState() {
 6     // TODO: implement createState
 7     return MyAppState("Hello World");
 8   }
 9 }
10 
11 class MyAppState extends State<MyApp> {
12 
13   @override
14   Widget build(BuildContext context) {
15     return ...
16   }
17  
18 }

仔細觀察主要由兩部分構成:StatefulWidget和State。