-
-
Save kranfix/e33d3a0a9c36a059191bffe477ccbcf9 to your computer and use it in GitHub Desktop.
Flutter fix: Inherited widget example
This file contains hidden or 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
// Fx for https://gist.github.com/stegrams/a2d17dc45bdae1ddfcc92cf6af96b80b/revisions#diff-a4501314e2bb2871a1a84da5ed71b87b | |
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
// Type: Foo<void> instead of Foo (=Foo<dynamic>) | |
home: Foo<void>(child: Bar(), txt: "Happy 😁"), | |
); | |
} | |
} | |
class Foo<T> extends InheritedWidget { | |
Foo({Key key, this.txt, this.child}) : super(key: key, child: child); | |
final String txt; | |
final Widget child; | |
// Adding generic T | |
static Foo of<T>(BuildContext context) => | |
context.dependOnInheritedWidgetOfExactType<Foo<T>>(); | |
@override | |
bool updateShouldNotify(Foo old) => true; | |
} | |
class Bar extends StatelessWidget { | |
@override | |
// Requesting for Foo<void> instead of Foo(=Foo<dynamic>) | |
Widget build(BuildContext ctx) => Text(Foo.of<void>(ctx)?.txt ?? "Sad 🤕"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment