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
There are two possible ways:
late
variables tonullable
to avoid lateInit errorChange
to
_loading
variable.Use
_loading
to avoid this issue