-1

I need to get a number from SharedPreferences and store it in a constant. But i couldn't manage to do it.

SharedPreferences sp = await SharedPreferences.getInstance();
const int index = sp.getInt('index')!;

This code throws this error:

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

I want to get the data once and never change it again. How can i achieve this?

Ercan Tomaç
  • 29
  • 1
  • 5
  • 2
    You can't const should be constant at compile time, and a value retrieved from shared prefrences is not known at compile time. – croxx5f Aug 23 '21 at 21:34

1 Answers1

0

Put final instead of const and await for it rather than awaiting for the instance.

SharedPreferences sp = SharedPreferences.getInstance();
final int index = await sp.getInt('index')!;
bonnopc
  • 755
  • 1
  • 7
  • 19
  • But i won't be able to use const widgets where i use that number if i make it final instead of const. I need to make widgets const, in order to boost the performance of the app. – Ercan Tomaç Aug 24 '21 at 11:35