在开发中我们经常会用到InheritedWidget,可以在它的任意子widget获取到数据
< 英 [ɪn'herɪtɪd]
import 'package:flutter/material.dart';
//数据共享!
class MyData extends InheritedWidget {
MyData({this.data, Widget child}) : super(child: child);
final int data; //需要在子Widget中共享的数据!
//提供一个方法让子Widget访问的共享数据!
static MyData of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<MyData>();
}
@override
bool updateShouldNotify(MyData oldWidget) {
return oldWidget.data != data;
}
}
class InheritedDemo extends StatefulWidget {
@override
_InheritedDemoState createState() => _InheritedDemoState();
}
class _InheritedDemoState extends State<InheritedDemo> {
int count = 1;
@override
Widget build(BuildContext context) {
return MyData(
data: count,
child: Column(
children: <Widget>[
Test1(),
RaisedButton(
child: Text('我是按钮'),
//setState!
onPressed: () => setState(() {
count++;
}),
)
],
),
);
}
}
class Test1 extends StatelessWidget {
// final count;
// Test1(this.count);
@override
Widget build(BuildContext context) {
return Test2();
}
}
class Test2 extends StatelessWidget {
// final count;
// Test2(this.count);
@override
Widget build(BuildContext context) {
return Test3();
}
}
class Test3 extends StatefulWidget {
// final count;
// Test3(this.count);
@override
_Test3State createState() => _Test3State();
}
class _Test3State extends State<Test3> {
@override
Widget build(BuildContext context) {
return Text(MyData.of(context).data.toString());
}
@override
void didChangeDependencies() {
print('didChangeDependencies');
super.didChangeDependencies();
}
}
网友评论