4

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 a FutureBuilder 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.

PeakGen
  • 21,894
  • 86
  • 261
  • 463

2 Answers2

5

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.

Ryosuke
  • 3,592
  • 1
  • 11
  • 28
0

With the current Flutter you have to use ScaffoldMessenger:

Global variable:

final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();

To display a SnackBar message from Future:

scaffoldMessengerKey.currentState!.showSnackBar(SnackBar(...));

Create app as:

Widget build(BuildContext context) {
  return MaterialApp(
    home: ScaffoldMessenger(
      key: scaffoldMessengerKey,
        child: Scaffold(
        appBar: AppBar(
        ...
marko
  • 417
  • 5
  • 5