Skip to content

Instantly share code, notes, and snippets.

@whataa
Last active November 29, 2019 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whataa/bef37322816ba8e91b8368a1f716b3ca to your computer and use it in GitHub Desktop.
Save whataa/bef37322816ba8e91b8368a1f716b3ca to your computer and use it in GitHub Desktop.
一个使用InheritedWidget的建议范例
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: Scaffold(
body: MyWidget(
Column(
children: <Widget>[
WidgetA(),
WidgetB()
],
)
),
),
));
}
class Wrapper extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MyWidget(
Column(
children: <Widget>[
WidgetA(),
WidgetB()
],
)
);
}
}
class MyWidget extends StatefulWidget {
final Widget child;
MyWidget(this.child);
@override
State<StatefulWidget> createState() {
return MyState();
}
}
class MyState extends State<MyWidget> {
int tmpData = 0;
@override
Widget build(BuildContext context) {
print('MyWidget build');
return MyInherited(
data: tmpData,
child: Container(
child: Column(
children: <Widget>[
widget.child,
FlatButton(
child: Text("Click me"),
onPressed: () {
setState(() {
print('onPressed');
tmpData += 1;
});
},
),
],
),
),
);
}
}
class MyInherited extends InheritedWidget {
final int data;
MyInherited({this.data, Widget child}) : super(child : child) {
print('MyInherited construct');
}
@override
bool updateShouldNotify(MyInherited oldWidget) {
bool result = oldWidget.data != this.data;
print('MyInherited updateShouldNotify result = $result');
return result;
}
static MyInherited of(BuildContext context) {
return context.inheritFromWidgetOfExactType(MyInherited);
}
}
class WidgetA extends StatelessWidget {
@override
Widget build(BuildContext context) {
print('WidgetA build');
int data = MyInherited.of(context).data;
return Text('WidgetA data = $data');
}
}
class WidgetB extends StatelessWidget {
@override
Widget build(BuildContext context) {
print('WidgetB build');
return Text('WidgetB');
}
}
@l1shu
Copy link

l1shu commented Nov 20, 2019

Wrapper 这个类有啥作用?不是在runApp就已经有了吗?

@whataa
Copy link
Author

whataa commented Nov 20, 2019

忽略它吧,把它替换到Scaffold也可以,本身这个文件是从项目里面扒出来改的,有些冗余代码不好意思

Copy link

ghost commented Nov 29, 2019

代码貌似还是跑不起来耶。提示Column's children must not contain any null values, but a null value was found at index 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment