Flutter-Provider 全局状态管理使用

2019-08-26  本文已影响0人  StevenHu_Sir

方案:

# 状态管理 Google 推出的 https://github.com/google/flutter-provide
provide: ^1.0.2

案例:

在页面上增加Text和一个Button.并故意使用StatelessWidget(不可变的页面)。并且用两个类隔离了。然后我们要点击按钮,增加数字数量,也就是把状态打通。

思路

import 'package:flutter/material.dart';
class Counter with ChangeNotifier {
  int value =0 ;
  increment(){
    value++;
    notifyListeners();
  }
}
import 'package:provide/provide.dart';
import './provide/counter.dart';
void main(){
  var counter =Counter();
  var providers  =Providers();
  providers
    ..provide(Provider<Counter>.value(counter));
  runApp(ProviderNode(child:MyApp(),providers:providers));
}
class Number extends StatelessWidget {
  

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top:200),
      child: Provide<Counter>(
        builder: (context,child,counter){
          return Text(
            '${counter.value}',
             style: Theme.of(context).textTheme.display1,
          );
        },
      ),
    );
  }
}
class MyButton extends StatelessWidget {
  

  @override
  Widget build(BuildContext context) {
    return Container(
      child:RaisedButton(
        onPressed: (){
          Provide.value<Counter>(context).increment();
        },
        child: Text('递增'),
      )
    );
  }
}
import 'package:flutter/material.dart';
import 'package:provide/provide.dart';
import '../provide/counter.dart';

class MemberPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Center(
        child: Provide<Counter>(
        builder: (context,child,counter){
          return Text(
            '${counter.value}',
             style: Theme.of(context).textTheme.display1,
          );
        },
      ),
      )
    );
  }
}

效果图

状态管理.gif

UI代码

import 'package:flutter/material.dart';


class CartPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Center(
        child: Column(
         children: <Widget>[
           Number(),
           MyButton()
         ],
        ),
      )
    );
  }
}

补充

多个 provide配置

使用 ProviderNode+providers

import './routers/routes.dart';
import './routers/application.dart';

void main() {

  // Provider 配置
  var counter = Counter();
  var providers = Providers();
  var childCategory = ChildCategory();
  var categoryGoodsListProvide= CategoryGoodsListProvide();
  providers
    ..provide(Provider<Counter>.value(counter))
    ..provide(Provider<ChildCategory>.value(childCategory))
    ..provide(Provider<CategoryGoodsListProvide>.value(categoryGoodsListProvide));
  runApp(ProviderNode(child: MyApp(), providers: providers));
}

案例:BottomNavBarProvider

1.依赖

provider: ^3.1.0

2.封装

import 'package:flutter/cupertino.dart';

class BottomNavBarProvider with ChangeNotifier {
  int _currentIndex = 0;

  get currentIndex => _currentIndex;

  set currentIndex(int index) {
    _currentIndex = index;
    notifyListeners();
  }
}

3.使用 (包裹一层ChangeNotifierProvider)

import 'package:flutter/material.dart';
import 'package:flutter_animations/chat_page.dart';
import 'package:flutter_animations/favorite_page.dart';
import 'package:flutter_animations/help_page.dart';
import 'package:flutter_animations/home_page.dart';
import 'package:flutter_animations/provider/model/bottom_nav_bar_provider.dart';
import 'package:provider/provider.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData(
        primarySwatch: Colors.deepOrange,
      ),
// 关键代码 1
      home: ChangeNotifierProvider<BottomNavBarProvider>(
        child: new MainPage(title: 'Flutter底部导航Provider版'),
        builder: (BuildContext context) => BottomNavBarProvider(),
      ),
    );
  }
}

class MainPage extends StatefulWidget {
  MainPage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MainPageState createState() => new _MainPageState();
}

class _MainPageState extends State<MainPage> {
  var currentTab = [
    HomePage(),
    FavoritePage(),
    ChatPage(),
    HelpPage(),
  ];

  @override
  Widget build(BuildContext context) {
    var provider = Provider.of<BottomNavBarProvider>(context);
    return new Scaffold(
      body: currentTab[provider.currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
// 关键代码 2
        currentIndex: provider.currentIndex,
        items: [
          BottomNavigationBarItem(
            icon: new Icon(Icons.home),
            title: new Text('首页'),
          ),
          BottomNavigationBarItem(
            icon: new Icon(Icons.favorite),
            title: new Text('收藏'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.chat),
            title: Text('聊天'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.help),
            title: Text('帮助'),
          ),
        ],
        onTap: (index) {
// 关键代码 3
          provider.currentIndex = index;
        },
      ),
    );
  }
}
上一篇下一篇

猜你喜欢

热点阅读