重学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。

坚持下去就能成功
原文地址:https://www.cnblogs.com/suoking/p/13825489.html