在數據管理上flutter package中的provide提供了良好使用體驗,與scoped_model中最大的特色在於有namespace的概念。 相關的使用方式,能夠參考文章Flutter UI使用Provide實現主題切換 本文將介紹provide中ProvideMulti屬性的使用方式git
本文相關連接github
/// UserModel
class UserModel with ChangeNotifier {
String name = 'Wanwu';
setAge(val) {
age = val;
notifyListeners();
}
}
/// ConfigModel
class ConfigInfo {
String theme = 'red';
}
class ConfigModel extends ConfigInfo with ChangeNotifier {
Future $setTheme(payload) async {
theme = payload;
notifyListeners();
}
}
/// init store
init({child, dispose = true}) {
final providers = Providers()
..provide(Provider.value(UserModel()))
..provide(Provider.value(AuthorModel()));
return ProviderNode(
child: child,
providers: providers,
dispose: dispose,
);
}
/// ...MainApp省略MainApp的內容
/// main
void main() => runApp(init(child: MainApp()));
複製代碼
ProvideMulti(
builder: builder,
child: child,
requestedValues: requestedValues,
requestedScopedValues: requestedScopedValues);
}
複製代碼
builder: (context, child, model)返回context, child, ProvidedValues值,ProvidedValues對應requestedValues提供的namespace。 requestedValues: []數組類型,即傳入數據模型對應的namespace,須要使用哪一個就傳入哪一個。[UserModel, ConfigModel] child: 傳入組件,在build中返回數組
ProvideMulti(
builder:(context, child, model) {
// 參數model是ProvidedValues的值,經過get方法和泛型能獲取到對應數據模型的數據。
UserModel user = model.get<UserModel>();
ConfigModel config = model.get<ConfigModel>();
return Container(
child: Text("name: ${user.name} , color: ${config.theme}")
)
},
requestedValues: [UserModel, ConfigModel]
)
複製代碼