Shared Preferences on iOS

Viewed 1355

I'm trying to use Shared Preferences but I have this strange behavior.

Im using:

shared_preferences: ^0.5.6+2

On a StateFull Widget on the initState I have this:

@override
  void initState() {
    super.initState();
    _testing()
  }


Future<void> _testing() async{
 print("starting")
 SharedPreferences prefs = await SharedPreferences.getInstance();
 await prefs.setInt('value', 1);
 print("saved?")
}

When I run the code with flutter run, I only get the print for "starting", not for "saved?".

The same exact code Im using for this project I've used to build an Android App and it worked just fine. But for iOS is not working.

What I am missing?

2 Answers

It works, there are no errors. Copy & paste and try it again:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {

  saveValue() async{
    print("Starting...");
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt('value', 1);
    print("Saved?");
  }


  @override
  void initState() {
    super.initState();
    saveValue();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Shared Preferences")),
      ),
    );
  }
}

It won't print because you are using the await before setting the int value.

await prefs.setInt('value', 1);

If you remove the await , then try checking the print value it will work fine.

Let me know if it works.

Related