Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

async await response not work #59

Open
farukaziz opened this issue Jul 26, 2021 · 1 comment
Open

async await response not work #59

farukaziz opened this issue Jul 26, 2021 · 1 comment

Comments

@farukaziz
Copy link

I like the get_server package but here I'm facing problem with async and await during response.

import 'package:get_server/get_server.dart' as gs;

final app = gs.GetServer();

app.get('/users', (ctx) async{
   List users = await UserService.getUsers();
   return gs.Json(users);
})
@mikeamir
Copy link

mikeamir commented Sep 17, 2021

For now, you can use the WidgetEmpty class which prevents the server from sending any response until the returned widget changes Its state. Thus you have multiple options that will do the same thing and any widget that can change state will do the trick:

1. FutureBuilder

return FutureBuilder(
          future: [YOUR ASYNC FUNCTION HERE],
          builder: (context, snapshot) {
            if (snapshot != null && snapshot.connectionState == ConnectionState.done) {
              return [YOUR RESPONSE, It could be Json() or a widget];
            } else {
            // This will prevent the server from sending any response until your async function completes
              return WidgetEmpty();
            }
          },
        );

2. StatefulWidget

class MyRequestHandlingWidget extends StatefulWidget {
  @override
  _MyRequestHandlingWidgetState createState() => _MyRequestHandlingWidgetState();
}

class _MyRequestHandlingWidgetState extends State<MyRequestHandlingWidget> {
  bool loaded = false;

  @override
  void initState() async {
    await myAsyncFunction();
    super.initState();
  }

  Future myAsyncFunction() async {
    // My Async Code
    // ...
    // ...
    // ...
    setState(() {
      loaded = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (loaded) {
      // YOUR RESPONSE HERE
      // return Json(.....);
      // return Widget(....);
    } else {
      return WidgetEmpty();
    }
  }
}

3. The usual GetX state management solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants