Search code examples
fluttertype-conversionsharedpreferences

I want to use shared preferences in flutter, but "Object" type can not be assigned to "bool"


codes like this:

import 'package:shared_preferences/shared_preferences.dart';
sharedUtil(String key,Object dataType,Object data) async{
  SharedPreferences prefs=await SharedPreferences.getInstance();
  switch(dataType){
    case bool:
      prefs.setBool(key, data);break;
    //other types...

  }
}

It reports that The argument type 'Object' can't be assigned to the parameter type 'bool*'. I don't know how to convert its type thank you!!


Solution

  • This error is because setBool method expects a bool as a data but your data is a type of Object. you can use type cast operator (as) to convert the type from Object to bool.

    Change your code as follows.

    import 'package:shared_preferences/shared_preferences.dart';
    sharedUtil(String key,Object dataType,Object data) async{
      SharedPreferences prefs=await SharedPreferences.getInstance();
      switch(dataType){
        case bool:
    
          prefs.setBool(key, data as bool);break;
        //other types...
    
      }
    }