Ad

Non-nullable Instance Field '_controller' Must Be Initialized

- 1 answer

  • The method 'TapBar' isn't defined for the type '_HomescreenState'.
  • Non-nullable instance field '_controller' must be initialized.

I'm getting above errors in my code.. how to correct those. appreciate your help on this..

import 'package:flutter/material.dart';


class Homescreen extends StatefulWidget {
  Homescreen({ Key? key }) : super(key: key);


  @override
  _HomescreenState createState() => _HomescreenState();
}

class _HomescreenState extends State<Homescreen> with SingleTickerProviderStateMixin{

   TabController _controller;   //error

@override
void initState(){
  super.initState();
  _controller =TabController(length: 4, vsync:this, initialIndex: 0);
}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Whatsapp Clone"),
        actions: [
          IconButton(icon: Icon(Icons.search), onPressed: () {}),
          IconButton(icon: Icon(Icons.more_vert), onPressed: () {}),
    ],
        bottom: TapBar(                //error
          _controller:_controller,
        ),
    ),
    );
  }
}
Ad

Answer

Because of null safety your variable must be initialzied when created, to fix this you can use late to tell it that it will be initialized after being created but before being used:

late final TabController _controller;
Ad
source: stackoverflow.com
Ad