Home > Back-end >  how to convert list of objects into specific data type
how to convert list of objects into specific data type

Time:09-01

Possible solution if there is any ? I lave a list of tabar like:

final tabList = [
      Icons.camera,
      "CHATS",
      "STATUS",
      "CALLS",
    ];

and i want to use this list like this way:

    TabBar(
tabs: tabList.map((e) => Tab()).toList();

and i want to set the value for icon and rest of them for text.

CodePudding user response:

You can't create a list with two data types. Either you can create a list of type String or of type IconData. Optionally if you want both the properties together in a list you might try creating a class for accommodating the two types.

import 'package:flutter/material.dart';

class TabItem {
  TabItem(this.name, this.icon);

  String name;
  IconData icon;
}

final tabList = [
  TabItem("Camera", Icons.camera),
  TabItem("Calls", Icons.phone),
  TabItem("Status", Icons.signal_wifi_statusbar_4_bar),
];

_getTabs() {
  return tabList.map((e) {
    return Tab(
      text: e.name,
      child: Icon(e.icon),
    );
  });
}

CodePudding user response:

You can have tabList of type List<dynamic>, but that may cause issues. Another solution would be to create an abstract class with child classes:

abstract class TabItem {}

class IconTab extends TabItem {
   final IconData icon;
   IconTab(this.icon);
}

class TitleTab extends TabItem {
   final String title;
   TitleTab(this.title);
}

and then set tabList of type List<TabItem>

final List<TabItem> tabList = [
  IconTab(Icons.camera),
  TitleTab("CHATS"),
  TitleTab("STATUS"),
  TitleTab("CALLS"),
];
  • Related