Error displaying user details stored in Flutter Secure Storage

Issue

I have been trying to display user details that are taken during Registration/Login in my Profile class, but am unable to display it. The details are displayed only when the Browser Window is resized or when an input is given (like uploading an image to profile). The details are not displayed automatically after registration or login.

The code for the screen is given below:

Future<Map<String, String>> getDetails() async {
  final Map<String, String> _details = {
    'firstname': '',
    'lastname': '',
    'username': '',
    'bio': '',
  };
  
  var storage = const FlutterSecureStorage();
  _details['username'] = (await storage.read(key: 'username')).toString();
  _details['firstname'] = (await storage.read(key: 'firstname')).toString();
  _details['lastname'] = (await storage.read(key: 'lastname')).toString();
  _details['bio'] = (await storage.read(key: 'bio')).toString();
  return _details;
}

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


  @override
  State<ProfileInfo> createState() => _ProfileInfoState();
}

class _ProfileInfoState extends State<ProfileInfo> {
  static String url = 'assets/artist_avatar.png';

  Map<String, String> details = {
    'firstname': '',
    'lastname': '',
    'username': '',
    'bio': '',
  };

  @override
  void initState() {
    Future.delayed(Duration.zero,() async {
        details = await getDetails();
    });
    super.initState();
  }

The code for displaying the details in the same class:

Text(details['firstname']!, //----------->displaying name
                style: const TextStyle(        
                  fontSize: 18.0,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                )),
            Text(details['username']!,   //----------->displaying username
                style: const TextStyle(
                  color: Colors.black45,
                  fontWeight: FontWeight.w100,
                )),

Solution

Try calling setState

Like so:

@override
void initState() {
  Future.delayed(Duration.zero,() async {
     details = await getDetails();
     setState((){});
  });
  super.initState();
}

Answered By – Josteve

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *