Flutter官方推荐的状态管理库provider的使用

Flutter官方推荐的状态管理库provider的使用,第1张

一、 Flutter 状态管理 通俗的讲 :当我们想在多个页面(组件 /Widget )之间共享状态(数据),或者一个页面(组 /Widget )中的多个子组件之间共享状态(数据),这个时候我们就可以用 Flutter 中的状 态管理来管理统一的状态(数据),实现不同组件直接的传值和数据共享。 现在 Flutter 的状态管理方案很多, redux bloc state provide provider 目前我们推荐使用 provider ,这个是官方提供的状态管理解决方案。相比其他状态管理库使 用起来比较方便 二、关于 flutter provider 库和 flutter provide p rovider provide 是两个库哦。 Flutter 官方推荐使用的是 provider 哦, provider flutter 官方出的。 provide 不是 Flutter 官方写的哦。 flutter provider 的使用 1 、配置依赖 provider: ^5.0.0 2 、新建一个文件夹叫 provider ,在 provider 文件夹里面放我们对于的状态管理类 3 、在 provider 里面新建 Counter.dart 4 Counter.dart 里面新建一个类继承 minxins ChangeNotifier 代码如下
import 'package:flutter/material.dart';
/// 组件之间状态更新
class Counter with ChangeNotifier{

  int _count = 0;  /// 初始状态
  int get count=>_count;  /// 获取状态
  incCount(){  /// 更新状态
    this._count++;
    notifyListeners(); /// 表示更新状态
  }

}

在main.dart 全局监听状态

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jdflutter/flutter_jdshop/routers/router.dart';
/// 导入provider
import 'package:provider/provider.dart';
import 'provider/Counter.dart';

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


class MyApp extends StatefulWidget {
  MyApp({Key? key}) : super(key: key);

  _MyAppState createState() => _MyAppState();
}
/// 全局监听状态
class _MyAppState extends State {
  @override
  Widget build(BuildContext context) {
    //ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true)..init(context);
    //ScreenUtil.init()
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_)=> Counter())
      ],
      child: ScreenUtilInit(
        designSize: Size(750, 1334),  //配置设计稿的宽度高度
        builder: () => MaterialApp(
          // home: Tabs(),
            initialRoute: '/',
            onGenerateRoute: onGenerateRoute,
            // 设置主题
            theme:ThemeData(
                primaryColor:Colors.white
            )
        ),
      ),
    );
  }
}

不同组件去更新状态

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../provider/Counter.dart';
class CartPage extends StatefulWidget {
 // const CartPage({Key? key}) : super(key: key);

  @override
  _CartPageState createState() => _CartPageState();
}

class _CartPageState extends State {
  @override
  Widget build(BuildContext context) {
    /// 获取状态值 Counter
    var counterProvider = Provider.of(context);
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          /// 调用 状态方法
          counterProvider.incCount();
        },
        child: Icon(Icons.add),
      ),
      body: Center(
        child: Text("${counterProvider.count}"),
      ),
    );
  }
}


import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../provider/Counter.dart';

class UserPage extends StatefulWidget {
  //const UserPage({Key? key}) : super(key: key);

  @override
  _UserPageState createState() => _UserPageState();
}

class _UserPageState extends State {
  @override
  Widget build(BuildContext context) {
    /// 获取状态值 Counter
    var counterProvider = Provider.of(context);
    return Center(
      child: Text("${counterProvider.count}"),
    );
  }
}

父子组件传参 调用

import 'package:flutter/material.dart';

class Cart with ChangeNotifier{
  int _count = 1;

  List _cartList=[]; //
 // int _cartNum = 0;

  int get carNum =>this._cartList.length;
  List get cartList=>this._cartList;

  addList(value){
    this._cartList.add(value);
    notifyListeners();
  }

  deleteData(value){
    this._cartList.remove(value);
    notifyListeners();

  }


}
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../provider/Cart.dart';

class CartItem extends StatefulWidget {
  const CartItem({Key? key}) : super(key: key);

  @override
  _CartItemState createState() => _CartItemState();
}

class _CartItemState extends State {
  @override
  Widget build(BuildContext context) {
    /// 父子组件之间通讯
    var cartProvider = Provider.of(context);
    return cartProvider.cartList.length>0?Column(
      children: cartProvider.cartList.map((value){
        return ListTile(
            title: Text("${value}"),
          trailing: InkWell(
            onTap: (){
              cartProvider.deleteData(value);
            },
            child: Icon(Icons.delete),
          ),

        );
      }).toList(),

    ):Text("");
  }
}

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../provider/Cart.dart';
class CartNum extends StatefulWidget {
  const CartNum({Key? key}) : super(key: key);

  @override
  _CartNumState createState() => _CartNumState();
}

class _CartNumState extends State {
  @override
  Widget build(BuildContext context) {
    var cartProvider = Provider.of(context);
    return Column(
      children: [
        Text("${cartProvider.carNum}")
      ],
    );
  }
}

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../provider/Counter.dart';
import '../Cart/CartItem.dart';
import '../Cart/CartNum.dart';
import '../../provider/Cart.dart';
class CartPage extends StatefulWidget {
 // const CartPage({Key? key}) : super(key: key);

  @override
  _CartPageState createState() => _CartPageState();
}

class _CartPageState extends State {
  @override
  Widget build(BuildContext context) {
    /// 获取状态值 Counter
    var counterProvider = Provider.of(context);
    var cartProvider = Provider.of(context);
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          /// 调用 状态方法
          counterProvider.incCount();
          ///给购物车列表增加数据
          cartProvider.addList('haha${counterProvider.count}');
        },
        child: Icon(Icons.add),
      ),
      body: Column(
        children: [
          Center(
            child: Text("统计数量:${counterProvider.count}",style: TextStyle(
                fontSize: 36,
                fontWeight: FontWeight.bold)),
          ),
          Divider(),
          /// 加载购物车列表的子组件
          CartItem(),
          Divider(height: 40),
          CartNum(),

        ],
      )

    );
  }
}


 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/994109.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存