flutter-----状态管理provider

前言

之前我都是用provide,不过这个已经被谷歌抛弃了,所以今天博主就去学习了provider,现在写一篇博客,分享给大家学习

技术栈

provider: ^3.0.0+1

实例代码分析

状态管理器

import 'package:flutter/foundation.dart';

class Counter with ChangeNotifier{
  int counter=0;

  

  addCounter(){
    counter++;
    notifyListeners();
  }
}

在主函数中集成provider

class myApp extends StatelessWidget {
  const myApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(builder:  (_) => Counter()),
      ],
      child: MaterialApp(
        title: 'provider学习',
        home: indexPage(),
      ),
    );
    
  }
}

使用provider

class indexPage extends StatelessWidget {
  const indexPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('学习provider'),
      ),
      body: Center(
        child: Text('${Provider.of<Counter>(context).counter}'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          Provider.of<Counter>(context).addCounter();
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

希望这篇博客可以帮助更多小伙伴

发布了50 篇原创文章 · 获赞 35 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_35905501/article/details/98587854