Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

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?

like image 903
Joey Yi Zhao Avatar asked Oct 23 '25 21:10

Joey Yi Zhao


1 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 .
like image 105
Nikhil Badyal Avatar answered Oct 26 '25 11:10

Nikhil Badyal