如何将 ListView 构建器与提供者一起使用?

How to use ListView builder with Providers?

我正在尝试使用 ListView Builder 和 Provider 创建水平可滚动卡片。

Like this one

有没有其他方法可以达到同样的效果?

它说

══╡ 小部件库捕获异常╞════════════════════════════════════════ ═══════════════════════ 构建 BookTile(脏)时抛出了以下 ProviderNotFoundError: 错误:在此 BookTile 小部件上方找不到正确的提供者

要修复,请:

我的代码

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/files.dart';
import 'bookitem.dart';

class BookTile extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final booksData = Provider.of<Files>(context);
    final books = booksData.items;

    return ListView.builder(
      scrollDirection: Axis.horizontal,
      itemCount: books.length,
      itemBuilder: (ctx, i) => ChangeNotifierProvider.value(
        value: books[i],
        child: BookItem(),
      ),
    );
  }
}

class BookItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final book = Provider.of<File>(context);
    return Container(
      width: 120,
      color: Colors.transparent,
      margin: EdgeInsets.only(right: 20),
      child: Card(
        child: Wrap(
          children: <Widget>[
            Image.network(book.cover),
            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    '${book.completion} %',
                    style: TextStyle(
                        color: Colors.black.withOpacity(0.5), fontSize: 12.4),
                  ),
                  IconButton(
                      icon: Icon(
                        Icons.more_horiz,
                        size: 14.5,
                      ),
                      onPressed: null)
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

这不是您的代码,但您会明白的

// provider with ChangeNotifier      
List<Client>? _clients = [];

  get clients => _clients;

  addClient(Client client) async {
    _clients!.add(client);
    notifyListeners();
  }

您想在哪里使用

Consumer<ClientProvider>(
          builder: (_, data, __) => Expanded(
            child: ListView.builder(
              itemCount: data.clients.length,
              itemBuilder: (context, index) {
                return ClientRow(data.clients[index]);
              },)


here is the sample Im doing now