Reputation: 1
I'm new on flutter. I just wanted to store best score value. I tried to use Shared Preferences but i got an error.
import 'package:shared_preferences/shared_preferences.dart';
int best;
setBest(int n) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt('best', n);
}
getBest() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
int intValue = prefs.getInt('best');
if (intValue == null) {
return 0;
}
return intValue;
}
I call this dart file an another dart file
'import .... as x'
This pages shows to the user their current score and best
int best = x.getBest();
@override
void initState() {
super.initState();
if (score > best) {
best = score;
x.setBest(score);
}
}
error message
Exception caught by widgets library
The following _TypeError was thrown building Builder:
type 'Future<dynamic>' is not a subtype of type 'int'
The relevant error-causing widget was MaterialApp lib\main.dart:9
When the exception was thrown, this was the stack
#0 new _QuizResultState package:quiz_game/pages/quiz_result.dart:16
#1 QuizResult.createState package:quiz_game/pages/quiz_result.dart:12
#2 new StatefulElement package:flutter/…/widgets/framework.dart:4591
#3 StatefulWidget.createElement package:flutter/…/widgets/framework.dart:894
Normal element mounting (115 frames)
Upvotes: 0
Views: 4082
Reputation: 171
When you put async
in a method, this method will return a Future<dynamic>
object, so in second block of code you try to put a future inside a int:
int best = x.getBest();
To solve this I suggest:
Future<int> best = x.getBest();
@override
void initState() async {
super.initState();
if (score > await best) {
best = Future.sync(score);
x.setBest(score);
}
}
Upvotes: 1