移动端中经常有这样的场景比如电商界面中商品详情页点击收藏后同步至列表页对于这种需求一般实现起来比较繁琐,而前端开发中经常听到redux等进行一些状态管理这方便了很多功能的实现而在flutter中也有状态管理Scoped_Model就是其中之一
本文简单的记录一下Scoped_Model的用法
先介绍一下Scoped_Model
A set of utilities that allow you to easily pass a data Model from a parent Widget down to it's descendants. In addition, it also rebuilds all of the children that use the model when the model is updated. This library was originally extracted from the Fuchsia codebase.
一组实用程序,允许您轻松地将数据模型从父窗口小部件传递给它的后代。此外,它还重建了模型更新时使用模型的所有子代。这个库最初是从 Fuchsia 基代码中提取的。
其中有一个概念就是InheritedWidget
InheritedWidget是Flutter中非常重要的一个功能型Widget,它可以高效的将数据在Widget树中向下传递、共享,这在一些需要在Widget树中共享数据的场景中非常方便,如Flutter中,正是通过InheritedWidget来共享应用主题(Theme)和Locale(当前语言环境)信息的。
我们先看一下如何使用Scoped_Model
先声明一个CounterModel官方文档中说明我们声明的CounterModel必须继承与Model
// Start by creating a class that has a counter and a method to increment it.
//
// Note: It must extend from Model.
class CounterModel extends Model {
int _counter = 0;
int get counter => _counter;
void increment() {
// First, increment the counter
_counter++;
// Then notify all the listeners.
notifyListeners();
}
}
点击进去观看Model源码
abstract class Model extends Listenable {
final Set<VoidCallback> _listeners = Set<VoidCallback>();
int _version = 0;
int _microtaskVersion = 0;
/// [listener] 将在Model更改时调用。
@override
void addListener(VoidCallback listener) {
_listeners.add(listener);
}
/// [listener] 移除时调用。
@override
void removeListener(VoidCallback listener) {
_listeners.remove(listener);
}
/// Returns the number of listeners listening to this model.
int get listenerCount => _listeners.length;
/// 仅当Model已更改时由[model]调用。
@protected
void notifyListeners() {
// 我们安排一个微任务来消除可能同时发生的多个更改。
if (_microtaskVersion == _version) {
_microtaskVersion++;
scheduleMicrotask(() {
_version++;
_microtaskVersion = _version;
// Convert the Set to a List before executing each listener. This
// prevents errors that can arise if a listener removes itself during
// invocation!
_listeners.toList().forEach((VoidCallback listener) => listener());
});
}
}
}
我们不难发现Model 继承了 Listenable,所以我们可以调用notifyListeners();
然后我们在需要使用这个Model的地方用ScopedModelDescendant来获取
class CounterHome extends StatelessWidget {
final String title;
CounterHome(this.title);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('You have pushed the button this many times:'),
// Create a ScopedModelDescendant. This widget will get the
// CounterModel from the nearest parent ScopedModel<CounterModel>.
// It will hand that CounterModel to our builder method, and
// rebuild any time the CounterModel changes (i.e. after we
// `notifyListeners` in the Model).
ScopedModelDescendant<CounterModel>(
builder: (context, child, model) {
return Text(
model.counter.toString(),
style: Theme.of(context).textTheme.display1,
);
},
),
Container(
child: RaisedButton(
onPressed: () {
Navigator.push(context,MaterialPageRoute(builder:(context) => ScopedTestWidget()));
},
child: Text(title),
),
),
],
),
),
// Use the ScopedModelDescendant again in order to use the increment
// method from the CounterModel
floatingActionButton: ScopedModelDescendant<CounterModel>(
builder: (context, child, model) {
return FloatingActionButton(
onPressed: model.increment,
tooltip: 'Increment',
child: Icon(Icons.add),
);
},
),
);
}
我们可以点击ScopedModelDescendant看一下它的内部结构
ScopedModelDescendant({
@required this.builder,
this.child,
this.rebuildOnChange = true,
});
可以看到ScopedModelDescendant<T extends Model>是一个Stateless Widget,它接收三个参数其中一个是builder我们再点击builder一看究竟
// Builds a child for a [ScopedModelDescendant].
typedef Widget ScopedModelDescendantBuilder<T extends Model>(
BuildContext context,
Widget child,
T model,
);
发现builder中有一个model他可以获取到我们定义的CountModel
看到这里似乎明白了
我们可以通过ScopedModelDescendant在任何一个widget里面拿到我们想要的model
我们新建一个dart文件
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import '../main.dart';
class ScopedTestWidget extends StatefulWidget {
@override
_ScopedTestWidgetState createState() => _ScopedTestWidgetState();
}
class _ScopedTestWidgetState extends State<ScopedTestWidget> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('lisi'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('You have pushed the button this many times:'),
// Create a ScopedModelDescendant. This widget will get the
// CounterModel from the nearest parent ScopedModel<CounterModel>.
// It will hand that CounterModel to our builder method, and
// rebuild any time the CounterModel changes (i.e. after we
// `notifyListeners` in the Model).
ScopedModelDescendant<CounterModel>(
builder: (context, child, model) {
return Text(
model.counter.toString(),
style: Theme.of(context).textTheme.display1,
);
},
),
],
),
),
// Use the ScopedModelDescendant again in order to use the increment
// method from the CounterModel
);
}
}
我们引入
import 'package:scoped_model/scoped_model.dart';
这样在我们想获取count的地方我们可以通过ScopedModelDescendant拿到达到了状态的同步
本篇文章就介绍到这里当然Scoped Model还有很多高级的用法因为才疏学浅还在研究中,以后将会进行补充