flutter狀態管理provider的基本使用

flutter有許多狀態管理插件,但provider是google官方推薦的,不要糾結了,跟着g爹走沒錯! 另外,用flutter開發的app聽電影已經上線,歡迎你們下載體驗:www.coolapk.com/apk/com.dcd…git

文章主要一點是想說下Selector的用法,由於發現沒人說過!github

一.添加配置provider

1.在pubspec.yaml中添加provider依賴,而後執行flutter packages getbash

provider: any
複製代碼

2.新建store.dart文件app

import 'package:flutter/material.dart';

class Store with ChangeNotifier {
  var _conut1 = 0, _conut2 = 0;

  get conut1 => _conut1;
  set conut1(val) {
    _conut1 = val;
    notifyListeners();
  }

  get conut2 => _conut2;
  set conut2(val) {
    _conut2 = val;
    notifyListeners();
  }
}
複製代碼

3.修改main.dart,用ChangeNotifierProvider包裹在最外層less

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      builder: (_) => Store(),
      child: MaterialApp(
        title: 'tdy-step',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: Home(),
      ),
    );
  }
}
複製代碼

二.在頁面使用全局數據

1.新建provider-test.dart文件,在initstate中能夠這樣獲取倉庫storeide

@override
  void initState() {
    super.initState();
    store = Provider.of<Store>(context, listen: false);
  }
複製代碼

2.在頁面中使用Selector獲取全局數據ui

Column(
              children: <Widget>[
                Selector<Store, dynamic>(
                    selector: (_, store) => store.count1,
                    builder: (_, data, __) => Text(data.toString())),
                SizedBox(
                  height: 100,
                ),
                RaisedButton(
                  child: Text('count1++'),
                  onPressed: () {
                    store.count1 = ++store.count1;
                  },
                )
              ],
            )

複製代碼

Selector重繪範圍比customer控制的更精細,它指定重繪只能有count1的變化觸發google

三.最後

demo代碼地址:github.com/saviourdog/…spa

相關文章
相關標籤/搜索