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

Initializing state of late variables in flutter

class _HomeViewState extends State<HomeView> {
  late UserInfo currentUser;

  @override
  void didChangeDependencies() async {
    super.didChangeDependencies();
    await dbService.getUserInfo(uid).then((value) {
      setState(() {
        currentUser = value!;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          Container(
            child: currentUser != null
                ? welcomeText(currentUser)
                : const Center(
                    child: CircularProgressIndicator(),
                  ),
          ),
...

Why is it not possible to do something like this?

The following LateError was thrown building HomeView(dirty, state: _HomeViewState#c79dc):
LateInitializationError: Field 'currentUser' has not been initialized.

Getting this error. How do I initialize Future/late variables and use them in Widgets without using FutureBuilder? FutureBuilder takes way too many lines of code.

initState() seems to be sync so it can’t be used

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 :

“Late” means “this variable will be initialized late”, It will be initialized late but never null, so currentUser never null, If the Late is not initialized, then we get the red screen of death. This is something that should never happen.

use UserInfo? currentUser instead of late UserInfo

class _HomeViewState extends State<HomeView> {
 UserInfo? currentUser;

  @override
  void didChangeDependencies() async {
    super.didChangeDependencies();
    await dbService.getUserInfo(uid).then((value) {
      setState(() {
        currentUser = value!;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          Container(
            child: currentUser != null
                ? welcomeText(currentUser!)
                : const Center(
                    child: CircularProgressIndicator(),
                  ),
          ),
...
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