Created
January 7, 2020 22:42
-
-
Save johnpryan/e0e6c35f8db1affe815077a81628c574 to your computer and use it in GitHub Desktop.
Custom notifications in Flutter
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 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