skip to Main Content

I am trying to get data from youtube API and using it in the UI part. I can get the data successfully but i am decalring a empty late variable and assigning a value to it through init state. The problem is, in the build method i used the "late declared" variable and it says LateInitializationError.

import 'package:flutter/material.dart';
import 'package:utube_api/models/popular_videos.dart';
import 'package:utube_api/utils/services.dart';
import 'package:cached_network_image/cached_network_image.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  
  // Variables i deaclared

  late PopularVideos _popularVideos;
  late Item _item;
  bool _loading = true;
  @override
  void initState() {
    // TODO: implement initState
    print("1");
    super.initState();
    _loading = true;
    _getPopularVideos();
  }

  _getPopularVideos() async {
    _popularVideos = await Services.getPopularVideos();
    _item = _popularVideos.items[0];
    print(_popularVideos.runtimeType);
    print(_item.runtimeType);
    setState(() {
      _loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Testing YOUTUBE API'),
      ),
      body: Container(
        color: Colors.white,
        child: Column(
          children: [Text(_item.snippet.channelTitle)],  # here i used the late varibale "_item" got error.
        ),
      ),
    );
  }
}

2

Answers


  1. There are two possible ways:

    1. You can change late variables to nullable to avoid lateInit error

    Change

    late PopularVideos _popularVideos;
    late Item _item;
    

    to

    PopularVideos? _popularVideos;
    Item? _item;
    
    1. You can use _loading variable.
     @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Testing YOUTUBE API'),
          ),
          body: Container(
            color: Colors.white,
            child: _loading? Center(child: CircularProgressIndicator()) : Column(
              children: [Text(_item.snippet.channelTitle)],
            ),
          ),
        );
      }
    
    Login or Signup to reply.
  2. Use _loading to avoid this issue

    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Testing YOUTUBE API'),
          ),
          body: Container(
            color: Colors.white,
            child: _loading? Center(child: CircularProgressIndicator()) : Column(
              children: [Text(_item.snippet.channelTitle)],
            ),
          ),
        );
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search