Home > front end >  LateInitializationError with Future
LateInitializationError with Future

Time:04-08

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;})

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();
    }
  }

}

CodePudding user response:

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

  • Related