Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to wait for SecureStorage in "initState" method?

I have the following code in my HomeScreen:

HomeScreen():

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
  int requestCount = 0;
  int selectedIndex = 0;
  List<Widget> listWidgets = [
    const ChatsScreen(),
    const PairedScreen(),
    const PeopleScreen(),
    const GroupsScreen(),
    const RequestsScreen()
  ];

//For tab selection
  void onItemTapped(int index) {
    setState(() {
      selectedIndex = index;
    });
  }

  String? username;

  getUsername()async{
    username = await SecureStorage().readSecureStorage('username');
  }

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

    getUsername();
    //Initialize Socket.IO
if (username != null) {
  SocketIO().initSocket(username!);
}
  }
.
.
.
}

I need to wait for SecureStorage to get username stored in the device (stored previously when the user has logged in successfully) and send it to socket.IO server in order to register socketID of the related user in the database.
When I run this code, username is null because initState() does not wait for SecureStorage. How can i fix this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can move the securestorage initialisation to a separate function and use an await inside that function to wait for it
This way, you can utilize an await statement within that function to ensure that it completes before proceeding. Here’s an example:

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

Future<void> initFunction() async {
  username = await SecureStorage().readSecureStorage('username');
  if (username != null) {
    SocketIO().initSocket(username!);
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading