androidflutterdartflutter-android

How to use shared preferences to populate a list of string items in a stateful widget in Flutter


I want to use shared preferences to store a list of names of files that the user has created. Upon launching the app, I want to show a list of those file names by reading them from shared preferences. How can I read shared preferences data (from an async function) and populate the data in a ListView which is placed inside a stateful widget?

class ListCard extends StatefulWidget {
  const ListCard({
    Key? key,
  }) : super(key: key);

  @override
  State<ListCard> createState() => _ListCardState();
}

class _ListCardState extends State<ListCard> {
  late List _dbList;

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

    _dbList = getDBNames().split(',');
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: _dbList.length,
      itemBuilder: (BuildContext context, int index) {
        return Card(
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          child: Padding(
            padding: const EdgeInsets.all(12.0),
            child: Text(
              _dbList[index],
            ),
          ),
        );
      },
    );
  }
}

The function to fetch the file names

getDBNames() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();

  var dbNames = prefs.getString('dbNames') ?? '';
  return dbNames.split(',');
}

This gives me the following error message

Class 'Future<dynamic>' has no instance method 'split'.
Receiver: Instance of 'Future<dynamic>'

How do I adapt my code to use Future?

On a side note, is there a way to read a list of sqlite databases on app launch and display the same in a ListView?


Solution

  • getDBNames is a Future method, you can use FutureBuilder

    class _ListCardState extends State<ListCard> {
      late final future = getDBNames();
      @override
      Widget build(BuildContext context) {
        return FutureBuilder<String?>(
            future: future,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                if (snapshot.data == null) return Text("got null data");
                final _dbList = snapshot.data!.split(",");
                return ListView.builder(
                  itemCount: _dbList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Card(
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10)),
                      child: Padding(
                        padding: const EdgeInsets.all(12.0),
                        child: Text(
                          _dbList[index],
                        ),
                      ),
                    );
                  },
                );
              }
              return CircularProgressIndicator();
            });
      }
    }
    

    Find more about FutureBuilder. Also you can save list on sharedPreference

    also you can use .then and call setState but not looks good that way.