Initializing state of late variables in flutter

Advertisements
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

>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(),
                  ),
          ),
...

Leave a ReplyCancel reply