Flutter - How to show a `snackbar` in `Future`
create a key for your scaffold like this:
var _key = new GlobalKey<ScaffoldState>();
then attach it with your scaffold:
Scaffold(
key: _key,
body: your_ui_here,
)
pass this key to your future
void _createUser(var key)
{
DataFetch().createUser(AppNavigation.getAPIUrl() +
"user/saveUser", user).then((String result){
key.currentState.showSnackbar(
Snackbar(content:Text("hello"))
);
});
}
You can pass this key anywhere and it will work as long as the attached Scaffold is not disposed.
Comments
-
PeakGen over 1 year
In my flutter app, I am sending data from mobile to server. That part is done like below.
register.dart
void _createUser() { DataFetch().createUser(AppNavigation.getAPIUrl() + "user/saveUser", user).then((String result){ print("RESULT IS: "+result); }); }
data_fetch.dart
Future<String> createUser(String url, User body) async { print("BODY: " + body.toJson().toString()); return http.post(url, body: convert.json.encode(body.toJson()), headers: { "Accept": "application/json", "content-type": "application/json" }).then((http.Response response) { final int statusCode = response.statusCode; print("RESPONSE: " + response.body); print("STATUS CODE: " + statusCode.toString()); if (statusCode < 200 || statusCode > 400 || response.body == null) { throw new Exception("Error while fetching data"); } else { return response.body; } }); }
My UI is in register.dart and data_fetch.dart is a separate class with methods for supporting various data pass work.
I need to show a
snackbar
until the data save completes. I know I can use aFutureBuilder
there is no use of attaching it as a widget where it returns some UI, because I have no UI to show after data is saved. I am trying to send data to server and I just need to indicate that.How can I do this? There seems no such facility in
Future
anyway.