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

LateInitializationError with Future

I hope you could help me!

Error saying ‘tables’ has not been initiliazed. But when I set tables = [] instead of

widget.data.then((result) {tables = result.tables;})

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

it works. I think the problem comes from my app state data which is a Future.

My simplified code:

class NavBar extends StatefulWidget {
  final Future<Metadata> data;

  const NavBar({Key? key, required this.data}) : super(key: key);

  @override
  State<NavBar> createState() => _NavBarState();
}

class _NavBarState extends State<NavBar> {
  late List<MyTable> tables;

  @override
  void initState() {
    widget.data.then((result) {
        tables = result.tables;
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
              child: buildPages(page.p)
            )
    );
  }

  Widget buildPages(index){
    switch (index) {
      case 0:
        return ShowTablesNew(tables: tables);
      case 1:
        return const Details();
      case 2:
        return const ShowTables();
      default:
        return const ShowTables();
    }
  }

}

>Solution :

Future doesn’t contain any data. It’s an asynchronous computation that will provide data "later". The initialization error happens because the variable ‘tables’ is marked as late init but is accessed before the future is completed, when in fact it’s not initialized yet.
Check this codelab for async programming with dart.

For your code you can use async/await in the initState method doing something like this

String user = '';

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

  void asyncInitState() async {
    final result = await fetchUser();
    setState(() {
      user = result;
    });
  }

but since you’re using a list of custom objects the most straightforward way is probably to use a FutureBuilder widget

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