Miles
Miles

Reputation: 1469

How can I use SharedPreferences to save a list of Strings in Flutter

I am trying to save a list of strings in flutter by using SharedPreferences. But my problem is that I have 8 different class in one .dart page and I want to display the saved strings on all the classes, so the SharedPreferences fonction has to be written outside of any class.

Here's one part of my 3000 line of code.

*`So my SharedPreferences fonction has to be outside of any classes (in this case here) and I need to be able to read it from the inside of the _MainScreenState class (in the text)`*


    class MainScreen extends StatefulWidget {
  @override
  _MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  @override
  Widget build(BuildContext context) {
    return Container(
      
     child:  Text('one of the saved string value has to appear here');
    );
  }
}

Upvotes: 0

Views: 107

Answers (1)

Benedikt J Schlegel
Benedikt J Schlegel

Reputation: 1939

Inserting a List into shared preferences is pretty straight forward. Have a look here: Can i put List into SharedPreferences in Flutter?

As for accessing it. SharedPreferences are available from anywhere in your App. So getting them to your classes should not be an issue. I would try with a static function, something like this:

class TestClass{
  //This is available from anywhere in your project
  //TestClass.getList();
  static List<String> getList(){
    //Get your list from preferences
    //and return it.
  }
}

Upvotes: 1

Related Questions