Home > Blockchain >  initState called after build drawer menu
initState called after build drawer menu

Time:01-11

I have a drawer menu in my scaffold, and I want to show some information from Flutter secure storage.

class DrawerMenu extends StatefulWidget {
  final Translations translations;
  final PageController controller;

  const DrawerMenu({
    Key? key,
    required this.translations,
    required this.controller,
  }) : super(key: key);

  @override
  State<DrawerMenu> createState() => _DrawerMenuState();
}

String? name;
String? email;

final FlutterSecureStorage storage = FlutterSecureStorage();

class _DrawerMenuState extends State<DrawerMenu> {
  @override
  void initState() {
    getInfo();
    super.initState();
  }

  getInfo() async {
    name = await storage.read(key: 'name');
    email = await storage.read(key: 'email');
  }

@override
  Widget build(BuildContext context) {
    Translations translations = Translations.of(context);
    return Drawer(
      backgroundColor: AppColors.secondaryColor,
      child: SafeArea(
        bottom: false,
        child: Column(
          children: [
            ClipOval(
              child: Container(
                color: AppColors.primaryColor,
                height: 60.0,
                width: 60.0,
                child: Center(
                  child: Text(
                    name![0],
                    style: TextStyle(
                        color: AppColors.secondaryColor,
                        fontSize: 30,
                        fontWeight: FontWeight.bold),
                  ),
                ),
              ),
            ),
      );
  }
}

The first time I have this error: _CastError (Null check operator used on a null value) But if I try to go next and re open drawer, so done!

I want to see the name in my drawer menu.

CodePudding user response:

You have to set the state after setting the value in getInfo(). Also, you have to check if the name is null or not before accessing it.

getInfo() async {
    name = await storage.read(key: 'name');
    email = await storage.read(key: 'email');
    setState({}); <-- add this
  }

@override
  Widget build(BuildContext context) {
    Translations translations = Translations.of(context);
    return Drawer(
      backgroundColor: AppColors.secondaryColor,
      child: SafeArea(
        bottom: false,
        child: Column(
          children: [
            ClipOval(
              child: Container(
                color: AppColors.primaryColor,
                height: 60.0,
                width: 60.0,
                child: Center(
                  child: Text(
                    name==null? "" : name![0] ?? "",  <-- update this
                    style: TextStyle(
                        color: AppColors.secondaryColor,
                        fontSize: 30,
                        fontWeight: FontWeight.bold),
                  ),
                ),
              ),
            ),
      );
  }
}

  • Related