flutter有許多狀態管理外掛,但provider是google官方推薦的,不要糾結了,跟著g爹走沒錯! 另外,用flutter開發的app聽電影已經上線,歡迎大家下載體驗:www.coolapk.com/apk/com.dcd…
文章主要一點是想說下Selector的用法,因為發現沒人說過!
一.新增配置provider
1.在pubspec.yaml中新增provider依賴,然後執行flutter packages get
provider: any
複製程式碼
2.新建store.dart檔案
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包裹在最外層
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中可以這樣獲取倉庫store
@override
void initState() {
super.initState();
store = Provider.of<Store>(context, listen: false);
}
複製程式碼
2.在頁面中使用Selector獲取全域性資料
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的變化觸發
三.最後
demo程式碼地址:github.com/saviourdog/…