0

I have an issue with flutter + GraphQL while using subscriptions. I'm using a web backend for flutter, and whenever the view is resized, this causes the subscription to be canceled and remade, spamming my backend with requests.

This makes sense because resizing the view makes flutter re-create the widget, and the widget includes the GraphQL subscription.

So I know my issue is a code architecture problem, not a flutter problem. However all of the examples I have found online of using GraphQL with flutter follow this exact same pattern. I am not sure how to organize my code to have the GraphQL subscription "outside" of the view, when the the subscription to execute depends on what view is being shown.

Any ideas on how I should be organizing my code?

Thanks for the help!

This is my current structure for presenting my data and fetching the information from GraphQL.

class PersonWidget extends StatelessWidget {

  PersonWidget({required this.personId});

  Widget build(BuildContext context) {
    return Subscription(
      options: SubscriptionOptions(
        document: gql(r'''
          subscription ($personId: Int!){
            person(where: {id: {_eq: $personId}}) {
              id
              first_name
              last_name
              email
              }
            }
          }
        '''),
        variables: <String, String>{
          'personId': personId.toString(),
        },
      ),
      builder: (result) {
        if (result.isLoading && result.data == null) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
        var person = result.data!['person'][0];

        return WidgetStructureGoesHere( ... );
      },
    );
  }
}
Alex Recarey
  • 20,178
  • 4
  • 25
  • 22
  • Could you try to make use of a `StatefulWidget` instead of a `StatelessWidget`? Curious if this might work here – kounex Oct 05 '21 at 12:15
  • @kounex That has to be it! I'm working on that now, if I extract the graphql subscription to the state of the widget, then in theory the state will be separate from the widget re-render. Thank you! – Alex Recarey Oct 05 '21 at 12:37
  • Yes that's what I hoped for! Please let me know if you finally managed to get it to work! :) – kounex Oct 05 '21 at 13:06

0 Answers0