'Flutter Global Function update Stateful Widget State
I am writing a Flutter app that uses a Global Function to handle Pushy.me notifications. This function needs to update a stateful widget's state.
I have tried a Global Key to access the widgets current state but it did nothing. I have tried an Eventify emitter, the emit and the listener didnt seem to line up.
import 'package:eventify/eventify.dart';
EventEmitter emitter = new EventEmitter();
GlobalKey<_WrapperScreenState> _key = GlobalKey<_WrapperScreenState>();
void backgroundNotificationListener(Map<String, dynamic> data) {
// Print notification payload data
print('Received notification: $data');
// Notification title
String notificationTitle = 'MyApp';
// Attempt to extract the "message" property from the payload: {"message":"Hello World!"}
String notificationText = data['message'] ?? 'Hello World!';
Pushy.notify(notificationTitle, notificationText, data);
emitter.emit('updateList',null,"");
try{
print(_key.currentState.test);
}
catch(e){
print(e);
}
// Clear iOS app badge number
Pushy.clearBadge();
}
class WrapperScreen extends StatefulWidget {
@override
_WrapperScreenState createState() => _WrapperScreenState();
}
Solution 1:[1]
You can try using events for this, using a StreamController or the event bus package. Your stateful widget would listen on a global event bus, and you can fire an event with the necessary information for the widget itself to use to update the state.
Something like this (using the event bus package):
// main.dart
EventBus eventBus = EventBus();
class MyEvent {}
void somewhereGlobal() {
// trigger widget state change from global location
eventBus.fire(MyEvent());
}
void main() {
...
}
// my_stateful_widget.dart
...
class _MyWidgetState extends State<MyWidget> {
@override
void initState() {
super.initState();
eventBus.on<MyEvent>().listen((event) {
// update widget state
print("update widget state");
});
}
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | f4ancyfl4amingo |
