Skip to content

Instantly share code, notes, and snippets.

@jtlapp
Created September 11, 2019 04:06
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 jtlapp/7e75f4e835a9ea112464efa6cde0a20b to your computer and use it in GitHub Desktop.
Save jtlapp/7e75f4e835a9ea112464efa6cde0a20b to your computer and use it in GitHub Desktop.
Flutter InheritedWidget sharing static state
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