jonataslaw / get_server

A backend server that makes it possible to program with Flutter syntax and reuse existing code
Apache License 2.0
477 stars 42 forks source link

async await response not work #59

Open farukaziz opened 3 years ago

farukaziz commented 3 years ago

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 commented 3 years ago

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