Sarthak
Sarthak

Reputation: 117

How to show ads in list view in flutter?

I've been trying to show ads in flutter app and package I'm using for is admob_flutter. I'm trying to show ads in a listview separated and here's the code for it:-

class ListWithAds extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    List example = ['a', 'b', 'c', 'd', 'e'];
    return Container(
      child: ListView.separated(
          itemBuilder: (context, index) {
            return Card(child: Text(example[index]));
          },
          separatorBuilder: (context, index) {
            return Container(
              child: Card(
                  color: Colors.white,
                  child: AdmobBanner(
                      adUnitId: "ca-app-pub-3940256099942544/6300978111",
                      adSize: AdmobBannerSize.SMART_BANNER)),
            );
          },
          itemCount: example.length),
    );
  }
}

But I get the error:-

the getter 'length' was called on null

How do I correct this error and get ads in listview?

Upvotes: 2

Views: 4412

Answers (1)

Deepak Ror
Deepak Ror

Reputation: 2234

Just put you exmaple array out of build method like:

List example = ['a', 'b', 'c', 'd', 'e'];

class ListWithAds extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
  
    return Container(
      child: ListView.separated(
          itemBuilder: (context, index) {
            return Card(child: Text(example[index]));
          },
          separatorBuilder: (context, index) {
            return Container(
              child: Card(
                  color: Colors.white,
                  child: AdmobBanner(
                      adUnitId: "ca-app-pub-3940256099942544/6300978111",
                      adSize: AdmobBannerSize.SMART_BANNER)),
            );
          },
          itemCount: example.length),
    );
  }
}

Upvotes: 4

Related Questions