Home > Software design >  type 'Sector' is not a subtype of type 'int' in type cast flutter problem?
type 'Sector' is not a subtype of type 'int' in type cast flutter problem?

Time:05-19

I wanted to display my Tabs using a sectors' list (Sector model) which I'm getting from Api like shown bellow:

SizedBox(
                    child: DefaultTabController(
                      initialIndex: 1,
                      length: sectorsProvider.sectorList.length,
                      child: DecoratedBox(
                        decoration: BoxDecoration(
                          //This is for background color
                          color: Colors.white.withOpacity(0.0),
                          //This is for bottom border that is needed
                          border: Border(
                            bottom: BorderSide(color: Colors.white, width: 0.4),
                          ),
                        ),
                        child: ListView(
                          shrinkWrap: true,
                          children: [
                            TabBar(
                                isScrollable: true,
                                indicatorColor: Colors.black,
                                controller: _tabController,
                                indicatorSize: TabBarIndicatorSize.label,
                                indicatorWeight: 3.0,
                                labelStyle: TextStyle(
                                  fontSize: 22.0,
                                ),
                                // unselectedLabelStyle: TextStyle(fontSize: 10.0, color: Colors.black26,),
                                tabs: (sectorsProvider.sectorList as List<Sector>).map((index) => Tab(text: sectorsProvider.sectorList[index as int].name)).toList(),
                                ),
                          ], 
                        ),
                      ),
                    ),
                  ),

I had the following error : type 'Sector' is not a subtype of type 'int' in type cast..

thanks for help!

CodePudding user response:

index as int

The plain fact that your compiler tells you this is not an int should make you think twice about what you are doing.

index in this case is of type Sector, because the callback you provide to map takes an element of the Iterable. In your case, since it's a List<Sector> that is a Sector.

So sectorsProvider.sectorList[index as int].name is not needed, all you need is index.name. Although it might be better to rename the variable:

tabs: (sectorsProvider.sectorList as List<Sector>).map((sector) => Tab(text: sector.name)).toList()

The fact that you need to cast sectorsProvider.sectorList to List<Sector> looks fishy, too. You shouldn't have to cast anything. Any time you do this, look for the improvement that would make the cast redundant, instead of casting.

  • Related