flutter 返回类型“Widget?”不是闭包上下文所要求的“Widget

0aydgbwb  于 2023-02-13  发布在  Flutter
关注(0)|答案(3)|浏览(154)

我使用消费者小部件来避免在null安全之前重新呈现,它工作正常...但是当我将提供者包升级到它时,它给了我一个错误,我上面提到过它不接受ListView.builder(),并说返回类型Widget?不是Widget,这是闭包上下文所要求的

Consumer<GreatPlaces>(
        child: Center(
          child: const Text(
            'Got no places yet, start adding some',
          ),
        ),
        builder: (ctx, greatPlaces, ch) => greatPlaces.items.length <= 0
            ? ch
            : ListView.builder(          ***//Here I got error***
                itemBuilder: (ctx, index) => Center(),
                itemCount: 5,
              ),
      ),
iqjalb3h

iqjalb3h1#

ch!上使用bang !操作

data.state.length <= 0
          ? child!
          : ListView.builder(
              itemBuilder: (context, index) => Container(),
              itemCount: 4,
            );
tzcvj98z

tzcvj98z2#

使用以下相同样品溶液;

body: Consumer<GreatPlaces>(
    child: const Center(
      child: Text('Got no places yet, start adding some!'),
    ),
    builder: (ctx, greatPlaces, ch) => greatPlaces.items.isEmpty
        ? ch!
        : ListView.builder(
            itemBuilder: (ctx, index) => ListTile(
              leading: CircleAvatar(
                backgroundImage: FileImage(
                  greatPlaces.items[index].image,
                ),
              ),
              title: Text(greatPlaces.items[index].title),
              onTap: () {},
            ),
            itemCount: greatPlaces.items.length,
          ),
  ),
p1tboqfb

p1tboqfb3#

请尝试以下代码:

Consumer<GreatPlaces>(
  child: Center(
    child: const Text(
      'Got no places yet, start adding some',
    ),
  ),
  builder: (ctx, greatPlaces, ch) => greatPlaces.items.length <= 0
      ? ch ?? Container() // You change Container to other widget
      : ListView.builder(
          itemBuilder: (ctx, index) => Center(),
          itemCount: 5,
        ),
),

相关问题