Search code examples
flutterlisttile

Error The element type 'List<Category>' can't be assigned to the list type 'Widget'


I need help showing subcategories of a parent category in Flutter list tiles. I have a model that has children as an array of subcategories. The subcategories can also have children as subcategories. Here is my model:

class Category{


  String name;
  String imageUrl;
  String slug;
  List children;
  Category({
    required this.name,
    required this.imageUrl,
    required this.slug,
    required this.children
  });

  factory Category.fromJson(Map<String, dynamic> json){

    return Category(
        name: json['name'] as String,
        imageUrl: json['imageUrl'] as String,
        slug: json['slug'],
        children: json['children']

    );
  }

}

And below is how I am trying to access my parent category and subcategory.

    class ShopPreview extends StatelessWidget {
  final Category category;
  final List<Category>? subcategories;
  const ShopPreview({Key? key, required this.category, this.subcategories} ) : super(key: key);

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Center(child: Text('Konnectmart')),
      ),
        body: ExpandableTheme(
          data: const ExpandableThemeData(
              iconColor: Colors.blue,
              useInkWell: true

          ),
          child: ListView.builder(
              itemCount: subcategories!.length,
              itemBuilder: (BuildContext context, int index)=>
                _buildList(subcategories![index])
                //final subcat = subcategories![index];

              ),
        )

    );
  }

}


Widget _buildList(Category list) {
  

  if (list.children.isEmpty) {
    return Builder(
        builder: (context) {
          return ListTile(
              onTap:() => Navigator.push(context, MaterialPageRoute(builder: (context) => ShopPreview(category:list))),
              leading: SizedBox(),
              title: Text(list.name.toString())
          );
        }
    );
  }
  return ExpansionTile(
    leading: Icon(Icons.add),
    title: Text(
      list.name.toString(),
      style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
    ),
    children: [
      list.children.map((e)=>Category.fromJson(e)).toList();


    ],
    // children: list.children.map(_buildList).toList(),
  );
}

I would appreciate any help. Thank you


Solution

  • you are just returning a list of categories where it expects a widget. You probably want to combine your commented out code with what you have. Something like this:

    children: list.children.map(e) => _buildList(Category.fromJson(e))).toList(),