Skip to content

Instantly share code, notes, and snippets.

@whataa
Last active September 15, 2019 08:57
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/f197d3136ac800ccbb254fa4974a732a to your computer and use it in GitHub Desktop.
Save whataa/f197d3136ac800ccbb254fa4974a732a to your computer and use it in GitHub Desktop.
一个使用InheritedWidget的错误范例
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: Scaffold(
body: MyWidget(),
),
));
}
class MyWidget extends StatefulWidget {
@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>[
WidgetA(),
WidgetB(),
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');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment