I want to access the shared preferences at the application startup and want to use this same object across the entire app by passing it to the classes. I am getting the following error:
The argument type 'Future' can't be assigned to the parameter type 'SharedPreferences'.
main.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:application/layouts/ScreenOne.dart';
import 'package:application/layouts/ScreenTwo.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
sharedPreferences() async {
return await SharedPreferences.getInstance();
}
final preferences = SharedPreferences.getInstance();
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MyApp',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: (preferences.getInt("login") == 1 ? ScreenOne(preferences) : ScreenTwo(preferences)),
);
}
}
I am unable to resolve this error. Is there anything I am doing wrong or missing? Thanks!!!
First of all, you defined function
sharedPreferences()
but did not use it later in the code - simply remove it.Furthermore, based on the documentation
SharedPreferences.getInstance()
returnsFuture<SharedPreferences>
and notSharedPreferences
, hence you get the following error. You can resolve the issue by getting theSharedPreferences
instance in the main method and then using constructor injection to provide thepreferences
object to theMyApp
: