Flutter - How to get value from shared preferences in a non-async methodFlutter: Access Stored Sharedpreference value from Other PagesHow to properly wait until future is complete in dartHow return Future from Future? Or this is prohibited in async library?Can i use the (facebook) parse library with google DART?Flutter: Best Practices of Calling Async Codes from UIUsing Futures to load config.json in FlutterHow to use Shared Preference in FlutterSharedPreferences.getInstance() before class constructorFlutter: Futures and shared preferencesFlutter: testing shared preferencesFlutter: shared preferenceshow to call dart package method from Flutter app

Is it true that, "just ten trading days represent 63 per cent of the returns of the past 50 years"?

Is It Possible to Have Different Sea Levels, Eventually Causing New Landforms to Appear?

Social leper versus social leopard

Resolving moral conflict

Is it really necessary to have a four hour meeting in Sprint planning?

What is the lowest voltage that a microcontroller can successfully read on the analog pin?

Which museums have artworks of all four Ninja Turtles' namesakes?

Allocating credit card points

What are these ingforms of learning?

I reverse the source code, you negate the output!

Could Apollo astronauts see city lights from the moon?

How do I deal with too many NPCs in my campaign?

How to deal with my team leader who keeps calling me about project updates even though I am on leave for personal reasons?

Is this a Sherman, and if so what model?

The quicker I go up, the sooner I’ll go down - Riddle

How to ask a man to not take up more than one seat on public transport while avoiding conflict?

Is it right to extend flaps only in the white arc?

How can an attacker use robots.txt?

Where does an unaligned creature's soul go after death?

Leaving a job that I just took based on false promise of a raise. What do I tell future interviewers?

Does Diablo III have a loot filter?

What benefits does the Power Word Kill spell have?

Norwegian refuses EU delay (4.7 hours) compensation because it turned out there was nothing wrong with the aircraft

Is it possible to encode a message in such a way that can only be read by someone or something capable of seeing into the very near future?



Flutter - How to get value from shared preferences in a non-async method


Flutter: Access Stored Sharedpreference value from Other PagesHow to properly wait until future is complete in dartHow return Future from Future? Or this is prohibited in async library?Can i use the (facebook) parse library with google DART?Flutter: Best Practices of Calling Async Codes from UIUsing Futures to load config.json in FlutterHow to use Shared Preference in FlutterSharedPreferences.getInstance() before class constructorFlutter: Futures and shared preferencesFlutter: testing shared preferencesFlutter: shared preferenceshow to call dart package method from Flutter app






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am trying to get some values saved in the SharedPreferences from a getter method of a class. But SharedPreferences.getInstance() returns a Future. Is there a way to obtain the SharedPreferences object in a non-async getter methods, for example:



import 'package:shared_preferences/shared_preferences.dart';

class MyClass
get someValue
return _sharedPreferencesObject.getString("someKey");




Is there something in Dart that is similar to .Result property in C#, for example getSomethingAsync().Result (https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1.result?view=netframework-4.7.2)?










share|improve this question


























  • Use a FutureBuilder stackoverflow.com/questions/54634418/…

    – Mazin Ibrahim
    Mar 28 at 16:05











  • Possible duplicate of Flutter: Access Stored Sharedpreference value from Other Pages

    – Richard Heap
    Mar 28 at 16:39











  • Hi @CopsOnRoad, I knew those solutions but my question is more about whether there's a way to wait for future object to return in a non-async method. I edited my question to make it a bit clearer (I hope).

    – Dean
    Mar 29 at 10:32












  • @Dean, I am not aware of your use case, but the good thing would be to get the SharedPreferences on app startup and after this use it when you need. You can also instantiate it in Splash screen of your app.

    – CopsOnRoad
    Mar 29 at 11:18











  • @CopsOnRoad, that's what I am doing at the moment. The answer to my question would be 'it's not possible'.

    – Dean
    Mar 29 at 12:14

















0















I am trying to get some values saved in the SharedPreferences from a getter method of a class. But SharedPreferences.getInstance() returns a Future. Is there a way to obtain the SharedPreferences object in a non-async getter methods, for example:



import 'package:shared_preferences/shared_preferences.dart';

class MyClass
get someValue
return _sharedPreferencesObject.getString("someKey");




Is there something in Dart that is similar to .Result property in C#, for example getSomethingAsync().Result (https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1.result?view=netframework-4.7.2)?










share|improve this question


























  • Use a FutureBuilder stackoverflow.com/questions/54634418/…

    – Mazin Ibrahim
    Mar 28 at 16:05











  • Possible duplicate of Flutter: Access Stored Sharedpreference value from Other Pages

    – Richard Heap
    Mar 28 at 16:39











  • Hi @CopsOnRoad, I knew those solutions but my question is more about whether there's a way to wait for future object to return in a non-async method. I edited my question to make it a bit clearer (I hope).

    – Dean
    Mar 29 at 10:32












  • @Dean, I am not aware of your use case, but the good thing would be to get the SharedPreferences on app startup and after this use it when you need. You can also instantiate it in Splash screen of your app.

    – CopsOnRoad
    Mar 29 at 11:18











  • @CopsOnRoad, that's what I am doing at the moment. The answer to my question would be 'it's not possible'.

    – Dean
    Mar 29 at 12:14













0












0








0


1






I am trying to get some values saved in the SharedPreferences from a getter method of a class. But SharedPreferences.getInstance() returns a Future. Is there a way to obtain the SharedPreferences object in a non-async getter methods, for example:



import 'package:shared_preferences/shared_preferences.dart';

class MyClass
get someValue
return _sharedPreferencesObject.getString("someKey");




Is there something in Dart that is similar to .Result property in C#, for example getSomethingAsync().Result (https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1.result?view=netframework-4.7.2)?










share|improve this question
















I am trying to get some values saved in the SharedPreferences from a getter method of a class. But SharedPreferences.getInstance() returns a Future. Is there a way to obtain the SharedPreferences object in a non-async getter methods, for example:



import 'package:shared_preferences/shared_preferences.dart';

class MyClass
get someValue
return _sharedPreferencesObject.getString("someKey");




Is there something in Dart that is similar to .Result property in C#, for example getSomethingAsync().Result (https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1.result?view=netframework-4.7.2)?







dart flutter






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 29 at 10:30







Dean

















asked Mar 28 at 15:59









DeanDean

1821 gold badge4 silver badges18 bronze badges




1821 gold badge4 silver badges18 bronze badges















  • Use a FutureBuilder stackoverflow.com/questions/54634418/…

    – Mazin Ibrahim
    Mar 28 at 16:05











  • Possible duplicate of Flutter: Access Stored Sharedpreference value from Other Pages

    – Richard Heap
    Mar 28 at 16:39











  • Hi @CopsOnRoad, I knew those solutions but my question is more about whether there's a way to wait for future object to return in a non-async method. I edited my question to make it a bit clearer (I hope).

    – Dean
    Mar 29 at 10:32












  • @Dean, I am not aware of your use case, but the good thing would be to get the SharedPreferences on app startup and after this use it when you need. You can also instantiate it in Splash screen of your app.

    – CopsOnRoad
    Mar 29 at 11:18











  • @CopsOnRoad, that's what I am doing at the moment. The answer to my question would be 'it's not possible'.

    – Dean
    Mar 29 at 12:14

















  • Use a FutureBuilder stackoverflow.com/questions/54634418/…

    – Mazin Ibrahim
    Mar 28 at 16:05











  • Possible duplicate of Flutter: Access Stored Sharedpreference value from Other Pages

    – Richard Heap
    Mar 28 at 16:39











  • Hi @CopsOnRoad, I knew those solutions but my question is more about whether there's a way to wait for future object to return in a non-async method. I edited my question to make it a bit clearer (I hope).

    – Dean
    Mar 29 at 10:32












  • @Dean, I am not aware of your use case, but the good thing would be to get the SharedPreferences on app startup and after this use it when you need. You can also instantiate it in Splash screen of your app.

    – CopsOnRoad
    Mar 29 at 11:18











  • @CopsOnRoad, that's what I am doing at the moment. The answer to my question would be 'it's not possible'.

    – Dean
    Mar 29 at 12:14
















Use a FutureBuilder stackoverflow.com/questions/54634418/…

– Mazin Ibrahim
Mar 28 at 16:05





Use a FutureBuilder stackoverflow.com/questions/54634418/…

– Mazin Ibrahim
Mar 28 at 16:05













Possible duplicate of Flutter: Access Stored Sharedpreference value from Other Pages

– Richard Heap
Mar 28 at 16:39





Possible duplicate of Flutter: Access Stored Sharedpreference value from Other Pages

– Richard Heap
Mar 28 at 16:39













Hi @CopsOnRoad, I knew those solutions but my question is more about whether there's a way to wait for future object to return in a non-async method. I edited my question to make it a bit clearer (I hope).

– Dean
Mar 29 at 10:32






Hi @CopsOnRoad, I knew those solutions but my question is more about whether there's a way to wait for future object to return in a non-async method. I edited my question to make it a bit clearer (I hope).

– Dean
Mar 29 at 10:32














@Dean, I am not aware of your use case, but the good thing would be to get the SharedPreferences on app startup and after this use it when you need. You can also instantiate it in Splash screen of your app.

– CopsOnRoad
Mar 29 at 11:18





@Dean, I am not aware of your use case, but the good thing would be to get the SharedPreferences on app startup and after this use it when you need. You can also instantiate it in Splash screen of your app.

– CopsOnRoad
Mar 29 at 11:18













@CopsOnRoad, that's what I am doing at the moment. The answer to my question would be 'it's not possible'.

– Dean
Mar 29 at 12:14





@CopsOnRoad, that's what I am doing at the moment. The answer to my question would be 'it's not possible'.

– Dean
Mar 29 at 12:14












3 Answers
3






active

oldest

votes


















2
















You can do it in initState() and after this call setState() to update your build() method. Other way is to use FutureBuilder()



SharedPreferences sharedPrefs;

@override
void initState()
super.initState();
SharedPreferences.getInstance().then((prefs)
setState(() => sharedPrefs = prefs);
);






share|improve this answer
































    2
















    I believe Dart currently doesn't support such feature that is equivalent to .Result in C#. The workaround would be using FutureBuilder or inject object in the initState() method as mentioned in other answers.






    share|improve this answer


































      1
















      You can use FutureBuilder()



      SharedPreferences sharedPrefs;

      @override
      Widget build(BuildContext context)
      return FutureBuilder(
      future: _getPrefs(),
      builder: (context, snapshot)
      if (snapshot.hasData)
      return YourFinalWidget();

      return CircularProgressIndicator(); // or some other widget
      ,
      );


      Future<void> _getPrefs() async
      sharedPrefs = await SharedPreferences.getInstance();






      share|improve this answer



























        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );














        draft saved

        draft discarded
















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55402021%2fflutter-how-to-get-value-from-shared-preferences-in-a-non-async-method%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2
















        You can do it in initState() and after this call setState() to update your build() method. Other way is to use FutureBuilder()



        SharedPreferences sharedPrefs;

        @override
        void initState()
        super.initState();
        SharedPreferences.getInstance().then((prefs)
        setState(() => sharedPrefs = prefs);
        );






        share|improve this answer





























          2
















          You can do it in initState() and after this call setState() to update your build() method. Other way is to use FutureBuilder()



          SharedPreferences sharedPrefs;

          @override
          void initState()
          super.initState();
          SharedPreferences.getInstance().then((prefs)
          setState(() => sharedPrefs = prefs);
          );






          share|improve this answer



























            2














            2










            2









            You can do it in initState() and after this call setState() to update your build() method. Other way is to use FutureBuilder()



            SharedPreferences sharedPrefs;

            @override
            void initState()
            super.initState();
            SharedPreferences.getInstance().then((prefs)
            setState(() => sharedPrefs = prefs);
            );






            share|improve this answer













            You can do it in initState() and after this call setState() to update your build() method. Other way is to use FutureBuilder()



            SharedPreferences sharedPrefs;

            @override
            void initState()
            super.initState();
            SharedPreferences.getInstance().then((prefs)
            setState(() => sharedPrefs = prefs);
            );







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 28 at 16:06









            CopsOnRoadCopsOnRoad

            21.8k5 gold badges61 silver badges51 bronze badges




            21.8k5 gold badges61 silver badges51 bronze badges


























                2
















                I believe Dart currently doesn't support such feature that is equivalent to .Result in C#. The workaround would be using FutureBuilder or inject object in the initState() method as mentioned in other answers.






                share|improve this answer































                  2
















                  I believe Dart currently doesn't support such feature that is equivalent to .Result in C#. The workaround would be using FutureBuilder or inject object in the initState() method as mentioned in other answers.






                  share|improve this answer





























                    2














                    2










                    2









                    I believe Dart currently doesn't support such feature that is equivalent to .Result in C#. The workaround would be using FutureBuilder or inject object in the initState() method as mentioned in other answers.






                    share|improve this answer















                    I believe Dart currently doesn't support such feature that is equivalent to .Result in C#. The workaround would be using FutureBuilder or inject object in the initState() method as mentioned in other answers.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 29 at 12:19









                    CopsOnRoad

                    21.8k5 gold badges61 silver badges51 bronze badges




                    21.8k5 gold badges61 silver badges51 bronze badges










                    answered Mar 29 at 12:17









                    DeanDean

                    1821 gold badge4 silver badges18 bronze badges




                    1821 gold badge4 silver badges18 bronze badges
























                        1
















                        You can use FutureBuilder()



                        SharedPreferences sharedPrefs;

                        @override
                        Widget build(BuildContext context)
                        return FutureBuilder(
                        future: _getPrefs(),
                        builder: (context, snapshot)
                        if (snapshot.hasData)
                        return YourFinalWidget();

                        return CircularProgressIndicator(); // or some other widget
                        ,
                        );


                        Future<void> _getPrefs() async
                        sharedPrefs = await SharedPreferences.getInstance();






                        share|improve this answer





























                          1
















                          You can use FutureBuilder()



                          SharedPreferences sharedPrefs;

                          @override
                          Widget build(BuildContext context)
                          return FutureBuilder(
                          future: _getPrefs(),
                          builder: (context, snapshot)
                          if (snapshot.hasData)
                          return YourFinalWidget();

                          return CircularProgressIndicator(); // or some other widget
                          ,
                          );


                          Future<void> _getPrefs() async
                          sharedPrefs = await SharedPreferences.getInstance();






                          share|improve this answer



























                            1














                            1










                            1









                            You can use FutureBuilder()



                            SharedPreferences sharedPrefs;

                            @override
                            Widget build(BuildContext context)
                            return FutureBuilder(
                            future: _getPrefs(),
                            builder: (context, snapshot)
                            if (snapshot.hasData)
                            return YourFinalWidget();

                            return CircularProgressIndicator(); // or some other widget
                            ,
                            );


                            Future<void> _getPrefs() async
                            sharedPrefs = await SharedPreferences.getInstance();






                            share|improve this answer













                            You can use FutureBuilder()



                            SharedPreferences sharedPrefs;

                            @override
                            Widget build(BuildContext context)
                            return FutureBuilder(
                            future: _getPrefs(),
                            builder: (context, snapshot)
                            if (snapshot.hasData)
                            return YourFinalWidget();

                            return CircularProgressIndicator(); // or some other widget
                            ,
                            );


                            Future<void> _getPrefs() async
                            sharedPrefs = await SharedPreferences.getInstance();







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 28 at 16:12









                            CopsOnRoadCopsOnRoad

                            21.8k5 gold badges61 silver badges51 bronze badges




                            21.8k5 gold badges61 silver badges51 bronze badges































                                draft saved

                                draft discarded















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55402021%2fflutter-how-to-get-value-from-shared-preferences-in-a-non-async-method%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현