Skip to content

Instantly share code, notes, and snippets.

@nhancv
Created December 12, 2018 05:56
Show Gist options
  • Select an option

  • Save nhancv/5e8433ab9c5be27a9a13f15dd59e1cb0 to your computer and use it in GitHub Desktop.

Select an option

Save nhancv/5e8433ab9c5be27a9a13f15dd59e1cb0 to your computer and use it in GitHub Desktop.
InheritedWidget
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyInheritedWidget(
counter: 0,
child: MyHomePage(title: 'Flutter Demo Home Page'),
),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
final MyInheritedWidget myInheritedWidget = MyInheritedWidget.of(context);
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'${myInheritedWidget.counter}',
style: Theme.of(context).textTheme.display1,
),
TestStateless(),
TestStateful()
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class MyInheritedWidget extends InheritedWidget {
MyInheritedWidget({
Key key,
@required Widget child,
this.counter,
}) : super(key: key, child: child);
final int counter;
static MyInheritedWidget of(BuildContext context) {
return context.inheritFromWidgetOfExactType(MyInheritedWidget);
}
@override
bool updateShouldNotify(MyInheritedWidget oldWidget) =>
counter != oldWidget.counter;
}
class TestStateless extends StatelessWidget {
@override
Widget build(BuildContext context) {
print('build TestStateless');
return Text('TestStateless');
}
}
class TestStateful extends StatefulWidget {
@override
_TestStatefulState createState() => _TestStatefulState();
}
class _TestStatefulState extends State<TestStateful> {
@override
Widget build(BuildContext context) {
print('build TestStateful');
return Text('_TestStatefulState');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment