Search code examples
androidflutterandroid-widgetflutter-dependenciesflutter-widget

How to use widget lists in ListView.builder?



class CardPage extends StatelessWidget {
  String title;
  String description;
  CardPage({Key key,this.title,this.description}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final ThemeData themeData = Theme.of(context);
    return Container(
      height: (108),
      child: Card(
        semanticContainer: true,
        clipBehavior: Clip.antiAliasWithSaveLayer,
        child: ElevatedButton(
          onPressed: () {},
          style: ElevatedButton.styleFrom(
            primary: Colors.white54,
          ),
          child: ListTile(
              title: Text(title,
                  style: themeData.textTheme.headline2),
              trailing: Padding(
                padding: const EdgeInsets.only(bottom: 8.0),
                child: Wrap(
                  spacing: 6,
                  children: [
                    IconButton(
                      onPressed: () {},
                      icon: Icon(Icons.fastfood, size: 25),
                    ),
                  ],
                ),
              ),
              subtitle: Text(description,
                  style: themeData.textTheme.subtitle1)),
        ),
      ),
    );
  }
}

This is my CardPage class. And this is my FavoritePage class

import 'package:flutter/material.dart';

import 'card_page.dart';

class FavoritesPage extends StatefulWidget {
  List<CardPage> cardList;

  FavoritesPage({Key key,
  this.cardList,
  }) : super(key: key);

  @override
  State<FavoritesPage> createState() => _FavoritesPageState();
}

class _FavoritesPageState extends State<FavoritesPage> {
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body:SafeArea(
        child: ListView.builder(
          itemCount:widget.cardList.length,
            itemBuilder: (BuildContext context, int index) {
              return widget.cardList;
            }
            ),
      ),
    );
  }
}

As you can see, i want to use widget.cardList in listView.builder but the error says:

The return type 'List<CardPage>' isn't a 'Widget', as required by the closure's context.

I just want to create a favoritePage like there are a lot of cards and i wanted to paste it another page which name is favoritePage but i couldn't do this.


Solution

  • As you can see, you are ignoring the index..
    use it like this:

     return widget.cardList[index];