最多见的场景是咱们在一个界面执行了某种操做,须要在另外一个界面的某个地方(例如一个变量)产生更新等效果,就须要进行界面之间的通讯数据库
本文将介绍四种方法来完成这种事bash
什么是scoped_model?app
Scoped_model是一个dart第三方库,提供了让您可以轻松地将数据模型从父Widget传递到它的后代的功能。此外,它还会在模型更新时从新渲染使用该模型的全部子项。,并且不管该widget是否是有状态的均可以进行更新,再一次build
框架
实现原理less
Scoped model使用了观察者模式,将数据模型放在父代,后代经过找到父代的model进行数据渲染,最后数据改变时将数据传回,父代再通知全部用到了该model的子代去更新状态。
ide
用途函数
能够进行全局公共数据共享,除了使用scoped_model也可使用shared_preferences、或者新建一个类将共享数据设置成static类的成员。ui
具体使用this
1 添加依赖spa
scoped_model: ^0.3.0复制代码
2 、建立Model
import 'package:scoped_model/scoped_model.dart';
class CountModel extends Model{
int _count = 0;
get count => _count;
void increment(){
_count++;
notifyListeners();
}
}复制代码
三、将model放在顶层
//建立顶层状态
CountModel countModel = CountModel();
@override
Widget build(BuildContext context) {
return ScopedModel<CountModel>(
model: countModel,
child: new MaterialApp(
home: TopScreen(),
),
);
}复制代码
四、在子界面中获取Model
@override
Widget build(BuildContext context) {
return ScopedModelDescendant<CountModel>(
builder: (context,child,model){
return Scaffold(
body: Center(
child: Text(
model.count.toString(),
style: TextStyle(fontSize: 48.0),
),
),
);
},
);
}复制代码
5 一个简单的demo能够直接运行
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
class CountModel extends Model{
int _count = 0;
get count => _count;
void increment()
{
_count++;
notifyListeners();
}
}
void main()
{
CountModel countModel = CountModel();
runApp(new ScopedModel(model: countModel, child: MaterialApp(
home: PageA(),
)));
}
class PageA extends StatefulWidget{
@override
State<StatefulWidget> createState() {
// TODO: implement createState
return new _PageA();
}
}
class _PageA extends State<PageA>
{
@override
Widget build(BuildContext context) {
// TODO: implement build
return ScopedModelDescendant<CountModel>(
builder: (context,child,model)
{
return Scaffold(
appBar: AppBar(
title: Text(model.count.toString()),
),
body: RaisedButton(
onPressed: (){model.increment();},
),
);
},
);
}
}复制代码
什么是InheritedWidget?
InheritedWidget 是一个特殊的 Widget,它将做为另外一个子树的父节点放置在 Widget 树中。该子树的全部 widget 都必须可以与该 InheritedWidget 暴露的数据进行交互。
为了更好理解概念,咱们看一个例子
class MyInheritedWidget extends InheritedWidget {
MyInheritedWidget({
Key key,
@required Widget child,
this.data,
}): super(key: key, child: child);
final data;
static MyInheritedWidget of(BuildContext context) {
return context.inheritFromWidgetOfExactType(MyInheritedWidget);
}
@override
bool updateShouldNotify(MyInheritedWidget oldWidget) => data != oldWidget.data;
}
复制代码
以上代码定义了一个名为 “MyInheritedWidget” 的 Widget,目的在于为子树中的全部 widget 提供某些『共享』数据。
如前所述,为了可以传播/共享某些数据,须要将 InheritedWidget 放置在 widget 树的顶部,这解释了传递给 InheritedWidget 基础构造函数的 @required Widget child 参数。
static MyInheritedWidget of(BuildContext context) 方法容许全部子 widget 经过包含的 context 得到最近的 MyInheritedWidget 实例(参见后面的内容)。
最后重写 updateShouldNotify 方法用来告诉 InheritedWidget 若是对数据进行了修改,是否必须将通知传递给全部子 widget(已注册/已订阅)。
所以,使用时咱们须要把它放在父节点
class MyParentWidget... {
...
@override
Widget build(BuildContext context){
return new MyInheritedWidget(
data: counter,
child: new Row(
children: <Widget>[
...
],
),
);
}
}复制代码
子结点如何访问InhertedWidget中的数据呢?
class MyChildWidget... {
...
@override
Widget build(BuildContext context){
final MyInheritedWidget inheritedWidget = MyInheritedWidget.of(context);
///
/// 此刻,该 widget 可以使用 MyInheritedWidget 暴露的数据
/// 经过调用:inheritedWidget.data
///
return new Container(
color: inheritedWidget.data.color,
);
}
}复制代码
InhertedWidget的高级用法
上文讲到的用法有一个明显的缺点是没法实现相似于Scoped_model的自动更新,为此,咱们将inhertedWidget依托于一个statefulWidget实现更新
场景以下:
为了说明交互方式,咱们作如下假设:
示例代码以下
class Item {
String reference;
Item(this.reference);
}
class _MyInherited extends InheritedWidget {
_MyInherited({
Key key,
@required Widget child,
@required this.data,
}) : super(key: key, child: child);
final MyInheritedWidgetState data;
@override
bool updateShouldNotify(_MyInherited oldWidget) {
return true;
}
}
class MyInheritedWidget extends StatefulWidget {
MyInheritedWidget({
Key key,
this.child,
}): super(key: key);
final Widget child;
@override
MyInheritedWidgetState createState() => new MyInheritedWidgetState();
static MyInheritedWidgetState of(BuildContext context){
return (context.inheritFromWidgetOfExactType(_MyInherited) as _MyInherited).data;
}
}
class MyInheritedWidgetState extends State<MyInheritedWidget>{
/// List of Items
List<Item> _items = <Item>[];
/// Getter (number of items)
int get itemsCount => _items.length;
/// Helper method to add an Item
void addItem(String reference){
setState((){
_items.add(new Item(reference));
});
}
@override
Widget build(BuildContext context){
return new _MyInherited(
data: this,
child: widget.child,
);
}
}
class MyTree extends StatefulWidget {
@override
_MyTreeState createState() => new _MyTreeState();
}
class _MyTreeState extends State<MyTree> {
@override
Widget build(BuildContext context) {
return new MyInheritedWidget(
child: new Scaffold(
appBar: new AppBar(
title: new Text('Title'),
),
body: new Column(
children: <Widget>[
new WidgetA(),
new Container(
child: new Row(
children: <Widget>[
new Icon(Icons.shopping_cart),
new WidgetB(),
new WidgetC(),
],
),
),
],
),
),
);
}
}
class WidgetA extends StatelessWidget {
@override
Widget build(BuildContext context) {
final MyInheritedWidgetState state = MyInheritedWidget.of(context);
return new Container(
child: new RaisedButton(
child: new Text('Add Item'),
onPressed: () {
state.addItem('new item');
},
),
);
}
}
class WidgetB extends StatelessWidget {
@override
Widget build(BuildContext context) {
final MyInheritedWidgetState state = MyInheritedWidget.of(context);
return new Text('${state.itemsCount}');
}
}
class WidgetC extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Text('I am Widget C');
}
}
复制代码
说明
在这个很是基本的例子中:
_MyInherited
是一个 InheritedWidget,每次咱们经过 ‘Widget A’ 按钮添加一个项目时它都会从新建立什么是key?
在 Fultter 中,每个 Widget 都是被惟一标识的。这个惟一标识在 build/rendering 阶段由框架定义。
该惟一标识对应于可选的 Key 参数。若是省略该参数,Flutter 将会为你生成一个。
在某些状况下,你可能须要强制使用此 key,以即可以经过其 key 访问 widget。
为此,你可使用如下方法中的任何一个:GlobalKey、LocalKey、UniqueKey 或 ObjectKey。
GlobalKey 确保生成的 key 在整个应用中是惟一的。
强制使用GlobalKey的方法
GlobalKey myKey = new GlobalKey();
...
@override
Widget build(BuildContext context){
return new MyWidget(
key: myKey
);
}
复制代码
使用GlobalKey访问State
class _MyScreenState extends State<MyScreen> {
/// the unique identity of the Scaffold
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context){
return new Scaffold(
key: _scaffoldKey,
appBar: new AppBar(
title: new Text('My Screen'),
),
body: new Center(
new RaiseButton(
child: new Text('Hit me'),
onPressed: (){
_scaffoldKey.currentState.showSnackBar(
new SnackBar(
content: new Text('This is the Snackbar...'),
)
);
}
),
),
);
}
}
复制代码
假设你有一个属于另外一个 Widget 的子树的 Widget,以下图所示。
使用步骤以下
为了暴露 其 State,Widget 须要在建立时记录它,以下所示:
class MyExposingWidget extends StatefulWidget {
MyExposingWidgetState myState;
@override
MyExposingWidgetState createState(){
myState = new MyExposingWidgetState();
return myState;
}
}
复制代码复制代码
为了让“其余类” 设置/获取 State 中的属性,Widget State 须要经过如下方式受权访问:
例子:
class MyExposingWidgetState extends State<MyExposingWidget>{
Color _color;
Color get color => _color;
...
}
复制代码复制代码
class MyChildWidget extends StatelessWidget {
@override
Widget build(BuildContext context){
final MyExposingWidget widget = context.ancestorWidgetOfExactType(MyExposingWidget);
final MyExposingWidgetState state = widget?.myState;
return new Container(
color: state == null ? Colors.blue : state.color,
);
}
}复制代码