Home > Mobile >  Non-nullable instance field '_tabController' must be initialized
Non-nullable instance field '_tabController' must be initialized

Time:10-19

I frustated over this code

_GenresListState(this.genres);

why it keeps showing the alert of _tabController must be initialized, im already put late constructor but the error is still going, this is the code where i put it:

class _GenresListState extends State<GenresList> with SingleTickerProviderStateMixin {
  final List<Genre> genres;
  _GenresListState(this.genres);
  TabController _tabController;
  @override
  void initState() {
    super.initState();

CodePudding user response:

If you provide to initialize before reading _tabController, you can include late

late TabController _tabController;

  @override
  void initState() {
   super.initState();
    _tabController = TabController(length: length, vsync: this)

More about working with tabs

CodePudding user response:

You have to initialize the tab controller, because it needs to populate you current layout with the accurate data needed for the screen to be built.

You can't give it values after the screen has been built, and flutter won't let you do it either because it needs those values.

  late TabController tabController;
  @override
  void initState() {
    tabController = TabController(length: 2, vsync: this);

    super.initState();
  }

  @override
  void dispose() {
    tabController.dispose();
    super.dispose();
  }

Notice that the value had to be stated in the initState so when the layout is being built, it builds correctly.

For you use case if you want to build with the list of genres, you do something like this

  late TabController tabController;
  @override
  void initState() {
    tabController = TabController(length: genres.length, vsync: this);

    super.initState();
  }

  @override
  void dispose() {
    tabController.dispose();
    super.dispose();
  }
  • Related