导入
状态管理简介
学习在 Flutter 和 GetX 中管理状态。
...
文本控件的当前状态
...
文本控件的更新状态
1class MyHomePage extends StatefulWidget { 2 const MyHomePage({Key? key}) : super(key: key); 3 4 5 State<MyHomePage> createState() => _MyHomePageState(); 6} 7 8class _MyHomePageState extends State<MyHomePage> { 9 int _counter = 0; 10 11 void _incrementCounter() { 12 setState(() { 13 _counter++; 14 }); 15 } 16 17 18 Widget build(BuildContext context) { 19 return Scaffold( 20 appBar: AppBar( 21 title: const Text('Flutter 示例首页'), 22 ), 23 body: Center( 24 child: Column( 25 mainAxisAlignment: MainAxisAlignment.center, 26 children: <Widget>[ 27 const Text( 28 '您点击按钮的次数为:', 29 ), 30 Text( 31 '$_counter', 32 style: Theme.of(context).textTheme.headline4, 33 ), 34 ], 35 ), 36 ), 37 floatingActionButton: FloatingActionButton( 38 onPressed: _incrementCounter, 39 tooltip: '增加', 40 child: const Icon(Icons.add), 41 ), 42 ); 43 } 44}
1class Controller extends GetxController {}
1class Controller extends GetxController { 2 int counter = 0; 3 4 void increment() { 5 counter++; 6 update(); 7 } 8}
1class MyHomePage extends StatelessWidget { 2 3 Widget build(BuildContext context) { 4 return Scaffold( 5 appBar: AppBar( 6 title: const Text('Flutter 示例首页'), 7 ), 8 body: Center( 9 child: Column( 10 mainAxisAlignment: MainAxisAlignment.center, 11 children: <Widget>[ 12 const Text( 13 '您点击按钮的次数为:', 14 ), 15 Text( 16 'counter', 17 style: Theme.of(context).textTheme.headline4, 18 ), 19 ], 20 ), 21 ), 22 floatingActionButton: FloatingActionButton( 23 onPressed: () {}, 24 tooltip: '增加', 25 child: const Icon(Icons.add), 26 ), 27 ); 28 } 29}
1class MyHomePage extends StatelessWidget { 2 3 Widget build(BuildContext context) { 4 return GetBuilder<Controller>( 5 init: Controller(), 6 builder: (controller) => Scaffold( 7 appBar: AppBar( 8 title: const Text('Flutter 示例首页'), 9 ), 10 body: Center( 11 child: Column( 12 mainAxisAlignment: MainAxisAlignment.center, 13 children: <Widget>[ 14 const Text( 15 '您点击按钮的次数为:', 16 ), 17 Text( 18 '${controller.counter}', // 访问 counter 变量 19 style: Theme.of(context).textTheme.headline4, 20 ), 21 ], 22 ), 23 ), 24 floatingActionButton: FloatingActionButton( 25 onPressed: controller.increment, // 使用 increment 方法 26 tooltip: '增加', 27 child: const Icon(Icons.add), 28 ), 29 ), 30 ); 31 } 32}