Home > Enterprise >  null safety in flutter
null safety in flutter

Time:10-15

How to Declare Field in class and initialize it in initState() function. I try two solution , still not working. first : declare the field and initialize inside initeState still not working. second : declare the field with ( ? ) operation but still give me error if I used the field as in dispose function tabController.dispose();

class _TabBarInsideAppBarDemoState extends State<TabBarInsideAppBarDemo>
     {
  TabController tabController; // **first:** error :on-nullable instance field 'tabController' must be initialized.
  //**second** TabController? tabController ; this also give me error in dispose function it says : The method 'dispose' can't be unconditionally invoked because the receiver can be 'null'.
  
  @override
  void initState() {
    super.initState();

    tabController = TabController(length: 3, vsync: this);
  }

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

  Widget getTabBar() {
    return TabBar(controller: tabController, tabs: [
      Tab(text: "Add", icon: Icon(Icons.add)),
      Tab(text: "Edit", icon: Icon(Icons.edit)),
      Tab(text: "Delete", icon: Icon(Icons.delete)),
    ]);
  }

  Widget getTabBarPages() {
    return TabBarView(controller: tabController, children: <Widget>[
      Container(color: Colors.red),
      Container(color: Colors.green),
      Container(color: Colors.blue)
    ]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          flexibleSpace: SafeArea(
            child: getTabBar(),
          ),
        ),
        body: getTabBarPages());
  }
}

CodePudding user response:

In flutter 2 you need to specify whether a parameter can be a nullable or non-nullable object if it is nullable you need to add ? next to data type like

TabController? tabController; 

But if you want to declare lazily then you can use late keyword.

late TabController tabController; 

This says to compiler that its not a null just that we are gonna assign value later. just like you are assigning it in initState.

Make sure you assign value before you access otherwise it throws exception.

code:

 late TabController tabController;
  
  @override
  void initState() {
    super.initState();

    tabController = TabController(length: 3, vsync: this);
  }

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