flutter3 State

2022-07-13  本文已影响0人  f8d1cf28626a

flutter3 状态管理

Whiget State Manage

问题:需要保留原来的数据怎么办呢? 这就涉及到今晚的重磅 有状态的Widget

state widget

StatefulWidget

class SharedCenter extends StatelessWidget{}

改为

class SharedCenter extends StatefulWidget{}
// MyApp
class KWidgetStateManage extends StatefulWidget {
  const KWidgetStateManage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _KStateManage();
}
 // 状态管理者
class _KStateManage extends State<KWidgetStateManage>{
  static num count = 0;
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      debugShowMaterialGrid: false,
      debugShowCheckedModeBanner: false, // 清除斜杠
      home: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(title: const Text('hello flutter'),),
        body: Center(
            child: Chip(label: Text('state flutter $count'),)
        ),
        floatingActionButton: FloatingActionButton(onPressed: (){setState((){
          count+=1;
        });},child: const Icon(Icons.add),),
      ),
    );
  }
}
---------------------------------------------------
main.dart中

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget{
  // key 保证了唯一定位,解除了增量渲染可能带来的bug
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return const KWidgetStateManage();
  }
}

总结:

上一篇 下一篇

猜你喜欢

热点阅读