06.Flutter之创建一个StatefulWidget(有状态组件)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gzx110304/article/details/86626762

Flutter之创建一个StatefulWidget(有状态组件)

一.StatelessWidget(无状态组件)与StatefulWidget(有状态组件)的区别

  • StatelessWidget: 无状态组件,它的属性不能被修改(所有的值都是final)
  • StatefulWidget:持有的状态会在组件的生命周期中发生改变

二.实现一个StatefulWidget

  • 实现一个StatefulWidget需要两个类

    1.创建一个有状态组件RandomWords(继承自StatefulWidget)

    class RandomWords extends StatefulWidget {
    
      @override
      State<StatefulWidget> createState() {
        return null;
      }
      
    }
    

    2.创建最小状态类,继承自RandomWordsState,并将生成单词对的代码放到Build方法中

    class RandomWordsState extends State<RandomWords> {
    
      @override
      Widget build(BuildContext context) {
        // TODO: implement build
        final wordPair = WordPair.random();
        return Text(wordPair.asPascalCase);
      }
    
    }
    

    3.在有状态组件RandomWords的createState方法中创建RandomWordsState实例

    class RandomWords extends StatefulWidget {
    
      @override
      State<StatefulWidget> createState() {
        return RandomWordsState();
      }
    
    }
    
  • 在MyApp类中,移除生成单词对的代码(这里直接注释掉),并将用于显示的Text组件替换成RandomWords组件

    class MyApp extends StatelessWidget {
    
      @override
      Widget build(BuildContext context) {
    //    final wordPair = new WordPair.random();
        return new MaterialApp(
          title: 'Welecom to Flutter',
          debugShowCheckedModeBanner: false, //去除右上角debug标识
          home: new Scaffold(
            appBar: new AppBar(
              title: new Text('Welecom to Flutter'),
            ),
            body: new Center(
    //          child: new Text('Hello World'),
    //          child: new Text(wordPair.asPascalCase),
                child: RandomWords(),
            ),
          ),
        );
      }
    
    }
    

猜你喜欢

转载自blog.csdn.net/gzx110304/article/details/86626762