The argument type 'Future<SharedPreferences>' can't be assigned to the parameter type 'SharedPreferences'

Issue

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!!!

Solution

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() returns Future<SharedPreferences> and not SharedPreferences, hence you get the following error. You can resolve the issue by getting the SharedPreferences instance in the main method and then using constructor injection to provide the preferences object to the MyApp:

Future<void> main() async { // <-- Notice the updated return type and async
  final preferences = await SharedPreferences.getInstance(); // <-- Get SharedPreferences instance
  
  runApp(
    MyApp(preferences: preferences), // <-- Inject (pass) SharedPreferences object to MyApp
  );
}

class MyApp extends StatelessWidget {
  final SharedPreferences preferences;
  
  const MyApp({
    required this.preferences,
  })

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'MyApp',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: (preferences.getInt("login") == 1 ? ScreenOne(preferences) : ScreenTwo(preferences)),
    );
  }
}

Answered By – mkobuolys

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *