I'm very new here. I'm slowly getting the hang of Flutter but a complete novice at Kotlin/Java integration. I'm trying to make a Flutter app where some data is updated at irregular occasions within Flutter istelf and then displayed on a home screen widget.
I don't want to update the Android widget regularly because there will likely not be anything to change each day, but only occasionally. While looking for ways to actually make the widget, I found this really helpful answer from bnxm and a good implementation on Github from timobaehr.
Taking that as an example to work through, what if I wanted to update the "result" shown on the home screen widget whenever a button in the app was pressed (or a background service is run), rather than at a set interval? Timobaehr uses the default Flutter counting app in his demo, so what could I do with this code that is run when a button is pressed?
Here is the update function in main.dart:
void onWidgetUpdate() {
WidgetsFlutterBinding.ensureInitialized();
const MethodChannel channel = MethodChannel('com.example.app/widget');
channel.setMethodCallHandler(
(call) async {
final id = call.arguments;
print('on Dart ${call.method}!');
return {
'id': id,
// Some data of type int - this is what I want to update
'value': counter,
};
},
);
}
Then below is the place in the code where the value gets updated, based on the default Flutter starting application. I've also moved int counter = 0;
to the top of the dart file so it can be used everwhere.
void _incrementCounter() {
setState(() {
counter++;
});
// How can I update the home screen widget from here?
// For example, send the new value of 'counter' to 'value' in the update function
// so that the new value is displayed on the home screen widget
}
Is it as simple as adding something in here or will it require a change in the Kotlin code somewhere else? Thanks for your help.
Edit: I should have said, calling onWidgetUpdate() from the increment function doesn't change the widget at all, so I assume there must be something else that needs to happen, maybe in the background Kotlin code or with MethodChannels, which I am not familiar with.
If you want to run it yourself to test, I cloned from timobaehr's Github project and just changed the 'value' to come from 'counter' and be an int instead of a double.