Skip to content

Instantly share code, notes, and snippets.

@johnpryan
Created January 7, 2020 22:42
Show Gist options
  • Save johnpryan/e0e6c35f8db1affe815077a81628c574 to your computer and use it in GitHub Desktop.
Save johnpryan/e0e6c35f8db1affe815077a81628c574 to your computer and use it in GitHub Desktop.
Custom notifications in Flutter
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp();
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State {
String message = 'no option selected';
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(),
body: NotificationListener<MyNotification>(
onNotification: (notification) {
setState(() {
message = 'You selected option ${notification.data}';
});
return true;
},
child: Center(
child: Column(
children: [
Text(message),
MyWidget(),
],
),
),
),
),
);
}
}
class MyNotification extends Notification {
final String data;
MyNotification(this.data);
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
RaisedButton(
child: Text('Option A'),
onPressed: () {
MyNotification('A').dispatch(context);
},
),
RaisedButton(
child: Text('Option B'),
onPressed: () {
MyNotification('B').dispatch(context);
},
),
],
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment