Created
January 8, 2020 17:23
-
-
Save rrousselGit/281870aa932f4e64f76aa9863b98462d to your computer and use it in GitHub Desktop.
Inherited notification listener
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
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file | |
// for details. All rights reserved. Use of this source code is governed by a | |
// BSD-style license that can be found in the LICENSE file. | |
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class InheritedNotificationListener<T> extends InheritedWidget { | |
InheritedNotificationListener({Key key, this.listener, Widget child}) | |
: super(key: key, child: child); | |
static void dispatch<T>(BuildContext context, T value) { | |
Type typeof<T>() => T; | |
final type = typeof<InheritedNotificationListener<T>>(); | |
final element = context.ancestorInheritedElementForWidgetOfExactType(type); | |
final widget = element?.widget as InheritedNotificationListener<T>; | |
widget?.listener(value); | |
} | |
final void Function(T value) listener; | |
@override | |
bool updateShouldNotify(InheritedWidget w) => false; | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return InheritedNotificationListener( | |
listener: (int value) { | |
print('received $value'); | |
}, | |
child: MaterialApp( | |
title: 'Flutter Demo', | |
debugShowCheckedModeBanner: false, | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: 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) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(widget.title), | |
), | |
body: Center( | |
child: RaisedButton( | |
onPressed: () { | |
InheritedNotificationListener.dispatch(context, 42); | |
}, | |
child: Text('dispatch'), | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment