Flutter学习之StatefulWidget有状态组件学习

97 阅读1分钟

使用StatefulWidget有状态组件,效果类似于SwiftUI中的@State状态绑定。比较好理解。


class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  int countNum = 1;
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        SizedBox(height:100),
        Text('$countNum'),
        SizedBox(height: 50),
        ElevatedButton(
            onPressed: (){
              //必须调用这个方法才能改变值,改变了之后Text会自动刷新.类似于SwiftUI.的动态值绑定
              setState(() {
                countNum++;
              });
            },
            child: Text('按钮')
        )
      ],
    );
  }
}