How can I solve `Const variables must be initialized with a constant value.` in flutter?

Viewed 1338

I have below code in Flutter to use graphql library:

import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';

var httpLink = HttpLink(
  'https://api.github.com/graphql',
);

var authLink = AuthLink(
  getToken: () => 'Bearer <YOUR_PERSONAL_ACCESS_TOKEN>',
);

final Link link = authLink.concat(httpLink);

ValueNotifier<GraphQLClient> client = ValueNotifier(
  GraphQLClient(
    link: link,
    // The default store is the InMemoryStore, which does NOT persist to disk
    cache: GraphQLCache(store: HiveStore()),
  ),
);

const provider = GraphQLProvider(
  client: client,
  child: MaterialApp(
    title: 'demo',
  ),
);

There is a compile error on the line client: client:

Const variables must be initialized with a constant value.
Try changing the initializer to be a constant expression

Why does it compliant about const? Does it relate to the library?

2 Answers

It complain because the const must be initialized with a constant value which is not in your case. As client can be anything at runtime. So you can't do this.

provider = GraphQLProvider(
  client: client,
  child: MaterialApp(
    title: 'demo',
  ),
);

Choices

  1. Replace client with some const value or make client itself a const.
  2. You can make provider final .

Method 1:

const provider

to

final provider

Method 2:

to

const provider = const GraphQLProvider(...)

but I am afraid that class does not support

Notice that const and final are very different in Dart(Flutter).

Related