Created
September 11, 2019 04:06
-
-
Save jtlapp/7e75f4e835a9ea112464efa6cde0a20b to your computer and use it in GitHub Desktop.
Flutter InheritedWidget sharing static state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
home: MyHomePage(), | |
); | |
} | |
} | |
// InheritedWidget with unchanging state | |
class User { | |
User(this.name); | |
final String name; | |
} | |
var currentUser = User("Frodo Baggins"); | |
class InheritedUser extends InheritedWidget { | |
InheritedUser({Key key, @required this.user, @required Widget child}) | |
: super(key: key, child: child); | |
final User user; | |
@override | |
bool updateShouldNotify(InheritedUser old) => user != old.user; | |
} | |
class MyHomePage extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return InheritedUser( | |
user: currentUser, | |
child: Scaffold( | |
appBar: AppBar( | |
title: Builder(builder: (context) { | |
final inherited = context.ancestorWidgetOfExactType(InheritedUser) | |
as InheritedUser; | |
return Text("Page for ${inherited.user.name}"); | |
}), | |
), | |
body: MyWidget(), | |
), | |
); | |
} | |
} | |
class MyWidget extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Center( | |
child: Builder(builder: (context) { | |
final inherited = | |
context.ancestorWidgetOfExactType(InheritedUser) as InheritedUser; | |
return Text( | |
'User: ${inherited.user.name}', | |
style: Theme.of(context).textTheme.display1, | |
); | |
}), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment