StatefulWidget 是有状态组件类。

    我们需要改变页面的状态就需要使用这个类:

    1. import 'package:flutter/material.dart';
    2. void main() => runApp(MyApp());
    3. class MyApp extends StatelessWidget {
    4. @override
    5. Widget build(BuildContext context) {
    6. return MaterialApp(
    7. title: 'Retrieve Text Input',
    8. home: Scaffold(
    9. appBar: AppBar(
    10. title: Text('Hello Flutter'),
    11. ),
    12. body: MyCustomForm(),
    13. ),
    14. );
    15. }
    16. }
    17. // StatefulWidget 有状态组件
    18. class MyCustomForm extends StatefulWidget {
    19. @override
    20. _MyCustomFormState createState() => _MyCustomFormState();
    21. }
    22. class _MyCustomFormState extends State<MyCustomForm> {
    23. int countNum = 0;
    24. @override
    25. Widget build(BuildContext context) {
    26. return Center(
    27. child: Column(
    28. children: [
    29. Text('$countNum'),
    30. ElevatedButton(
    31. child: Text('按钮'),
    32. onPressed: () {
    33. // 注意 , 需要调用 setState
    34. setState(() {
    35. this.countNum++;
    36. });
    37. },
    38. ),
    39. ],
    40. ),
    41. );
    42. }
    43. }