简体   繁体   English

Flutter GraphQl 查询不返回当前数据

[英]Flutter GraphQl query does not return current data

I am a little bit confused on why a GraphQL query returning a list of items does not get updated.我有点困惑为什么返回项目列表的 GraphQL 查询没有得到更新。 Say I have a list of three items, then I add another item and rebuild the widget.假设我有一个包含三个项目的列表,然后我添加另一个项目并重建小部件。 The widget still only shows the first three items, even though I can see that new item has been created in the database.小部件仍然只显示前三个项目,即使我可以看到数据库中已经创建了新项目。 I am unsure if this is a cache problem.我不确定这是否是缓存问题。 I have tried to fetch data from the.network only, but that does not work either.我试图仅从 .network 获取数据,但这也不起作用。

The client used in the GraphQLProvider is instantiated like this: GraphQLProvider 中使用的客户端实例化如下:

Future<ValueNotifier<GraphQLClient>> _getClient() async {
    final HttpLink httpLink = HttpLink(
      Constants.apiURL,
      defaultHeaders: {
        'X-Parse-Application-Id': Constants.kParseApplicationId,
        'X-Parse-Client-Key': Constants.kParseClientKey,
      },
    );

    // initialize Hive and wrap the default box in a HiveStore
    Directory directory = await pathProvider.getApplicationDocumentsDirectory();
    final store = await HiveStore.open(path: directory.path);
    return ValueNotifier(
      GraphQLClient(
        cache: GraphQLCache(store: store),
        link: httpLink,
      ),
    );
  }

And the page looks like this.页面看起来像这样。 When a new forum post is created, setstate() is called and the widget rebuilds.创建新的论坛帖子时,调用 setstate() 并重建小部件。 However, the line List<dynamic> forumEntries = result.data?["getForumEntries"];但是,行List<dynamic> forumEntries = result.data?["getForumEntries"]; still returns the old list of data without the new entry.仍然返回没有新条目的旧数据列表。 I have the same problem in a few other places as well.我在其他几个地方也有同样的问题。

class FeedWidget extends StatefulWidget {
  const FeedWidget({Key? key}) : super(key: key);

  @override
  State<FeedWidget> createState() => _FeedWidgetState();
}

class _FeedWidgetState extends State<FeedWidget> {
  final TextEditingController controller = TextEditingController();

  void _createForumPost() async {
    Map<String, dynamic> inputVariables = {
      "questionText": controller.text,
    };

    GraphQLClient client = GraphQLProvider.of(context).value;
    await client.query(
      QueryOptions(
        document: gql(GraphQLQueries.createForumPost),
        variables: inputVariables,
      ),
    );

    setState(() {
      controller.text = "";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Query(
      options: QueryOptions(
          fetchPolicy: FetchPolicy.networkOnly,
          document: gql(GraphQLQueries.getForumEntries),
      ),
      builder: (QueryResult result,
          {VoidCallback? refetch, FetchMore? fetchMore}) {
        if (result.hasException) {
          return Text(result.exception.toString());
        }
        if (result.isLoading) {
          return const Center(child: CircularProgressIndicator());
        }

        List<dynamic> forumEntries = result.data?["getForumEntries"];

        return Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: controller,
                    keyboardType: TextInputType.multiline,
                    maxLines: null,
                    autocorrect: false,
                    decoration: InputDecoration(
                      fillColor: Theme.of(context).colorScheme.surface,
                      labelText: "Content",
                      filled: true,
                      border: InputBorder.none,
                    ),
                  ),
                ),
                const Padding(padding: EdgeInsets.symmetric(horizontal: 3)),
                CustomIconButton(
                  padding: EdgeInsets.zero,
                  icon: const Icon(Icons.send),
                  onPressed: () => _createForumPost(),
                ),
              ],
            ),
            const Padding(padding: EdgeInsets.only(bottom: 10)),
            Expanded(
              child: ListView.builder(
                shrinkWrap: true,
                itemCount: forumEntries.length,
                itemBuilder: (BuildContext context, int index) {
                  Map<String, dynamic> entry = forumEntries[index];
                  return ForumEntryWidget(entry);
                },
              ),
            ),
          ],
        );
      },
    );
  }
}

Hellow there, i was stucked with this and solved easily using refetch functions returned by Query, as your CustomIconButton are inside the Query you can replace _createForumPost() by refetch(), in my case i use on the RefreshIncator creating a function Future who calls the refetch method.你好,我被这个问题困住了,使用查询返回的 refetch 函数很容易解决,因为你的 CustomIconButton 在查询中,你可以用 refetch() 替换 _createForumPost(),在我的例子中,我在 RefreshIncator 上使用创建一个 function Future 谁调用重新获取方法。

 @override Widget build(BuildContext context) { // resp = ListView(); return Scaffold( body: Query( options: QueryOptions( document: gql(documentQ), fetchPolicy: FetchPolicy.noCache, cacheRereadPolicy: CacheRereadPolicy.ignoreAll, optimisticResult: true), builder: (QueryResult result, {Refetch? refetch, FetchMore? fetchMore}) { if (result.isLoading) { return const Center(child: CircularProgressIndicator()); } if (result.data == null) { return const Center(child: Text('Nenhum tour por perto')); } return _toursView(result, refetch); }, ), ); } RefreshIndicator _toursView(QueryResult result, refetch) { // print(result.data?['tourAll']); Future<void> refresh(refetch) { return refetch(); } final toursList = result.data?['tourAll']; return RefreshIndicator( onRefresh: () => refresh(refetch), child: ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM