美文网首页
flutter Provider 学习demo

flutter Provider 学习demo

作者: 壹点微尘 | 来源:发表于2021-05-05 15:56 被阅读0次
    import 'package:flutter/foundation.dart';
    import 'package:flutter/material.dart';
    import 'package:provider/provider.dart';
    
    void main() {
      runApp(
        ChangeNotifierProvider(
          create: (_) => Counter(),
          child: const MyApp(),
        ),
      );
    }
    
    class Counter with ChangeNotifier {
      int _count = 0;
    
      int get count => _count;
    
      void increment() {
        _count++;
        notifyListeners();
      }
    }
    
    class MyApp extends StatelessWidget {
      const MyApp({Key key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return const MaterialApp(
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatelessWidget {
      const MyHomePage({Key key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('轻松上手provider'),
          ),
          body: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              children: const <Widget>[
                Text('点击按钮看看效果。'),
    
                /// 性能优化:这里将会频繁触发build的操作封装到单独的widget中来避免对整个页面频繁的build
                Count(),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            key: const Key('点我'),
    
            ///性能优化: 在这里调用`context.read`而不是`context.watch`,主要是为了避免当Counter变化时而带来的rebuild
            onPressed: () => context.read<Counter>().increment(),
            tooltip: '+1',
            child: const Icon(Icons.add),
          ),
        );
      }
    }
    
    class Count extends StatelessWidget {
      const Count({Key key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Text(
    
            ///使用 `context.watch` 可以在`Counter`改变之后重新构建Count
            '${context.watch<Counter>().count}',
            key: const Key('counterState'),
            style: Theme.of(context).textTheme.headline4);
      }
    }
    
    

    相关文章

      网友评论

          本文标题:flutter Provider 学习demo

          本文链接:https://www.haomeiwen.com/subject/dyzkdltx.html