Reputation: 7125
I have a statefull widged where a button has
onPressed: _exportData,
where _exportData defined this way
Future<void> _exportData() async {
...
setState(() {
_message = 'A message'; // I want to use localization string here
});
}
I need to pass localization string into the above setState() and I do it this way
Lang.key(ctx, 'about')
i.e. I need to pass the context there, but when I try to make it like this
onPressed: _exportData(ctx), // the error here
and
Future<void> _exportData(BuildContext ctx) async {...
there is an error on onPressed
The argument Future can not be assigned to the parameter type 'void Function()'
How cat I pass context inside _exportData or how can I use localization string from inside the _exportData?
update: actualy there was no need to pass context into _exportData, because context is awailable inside state class
Upvotes: 0
Views: 79
Reputation: 792
onPressed: () async { await _exportData(context) }
Make this change and let us know.
EDIT:
onPressed: _exportData(ctx), // the error here
You cannot do this because you can only pass a reference to a function in onPressed. If you want to pass arguments to a function, you'll have to do it the way I have shown above (although, it needs not to be asynchronous necessarily). Function name without the opening and a closing parenthesis is the reference while the one with the parenthesis is the actual function call.
The reason for this is that onPressed takes a reference/address to the function/pointer and not the actual function call. So if we had to pass the argument (context in your case) by your way, we will need to put the parenthesis around the argument making it a function call and not a reference hence executing it as soon as the build method runs and not when onPressed triggers it.
The way I showed you assigns an anonymous function to onPressed. See, there is no parenthesis in the end, so not executing it straight away and acting as a reference to a function. I put an async and await there because your _exportData function returns a future.
Hope that clears your doubt!
Upvotes: 1