Flutter Provider软件包无法通知侦听器

问题描述

class _LoadAssetState extends State<LoadAsset> {
  @override
  void initState() {
    load().then((val) => setState(() {
          Books().addBook(val);
          print('added');
        }));
    super.initState();
  }


@override
  Widget build(BuildContext context) {
    var booksData = Provider.of<Books>(context);
    var books = booksData.items;
    print(books.length);
    return GridView.builder(
      padding: const EdgeInsets.all(10.0),itemCount: books.length,itemBuilder: (ctx,i) => ChangeNotifierProvider.value(
        value: books[i],child: BookItem(),),gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,childAspectRatio: 3 / 2,crossAxisspacing: 10,mainAxisspacing: 10,);
  }
  Future<Book> load() async {
    WidgetsFlutterBinding.ensureInitialized();

    var targetFile = await rootBundle.load('assets/eBooks/Power.epub');
    Uint8List audioUint8List = targetFile.buffer
        .asUint8List(targetFile.offsetInBytes,targetFile.lengthInBytes);
    List<int> bytes = audioUint8List.cast<int>();
    EpubBook epubBook = await EpubReader.readBook(bytes);

    String title = epubBook.Title;
    String author = epubBook.Author;
    List<String> authors = epubBook.AuthorList;
    img.Image cover = epubBook.CoverImage;
    print(authors);

    io.Directory tempDir = await getTemporaryDirectory();

    img.Image thumbnail = img.copyResize(cover,width: 120,height: 180);
    io.File('${tempDir.path}/Power.jpg')
        .writeAsBytesSync(img.encodeJpg(thumbnail));
    print('loaded');
    return Book(id: DateTime.Now().toString(),title: title,authors: authors);
  }
}
即使在Books()中使用addBook方法添加obj之后,

books.length也返回0。通知侦听器在addBook方法中。图书已加载并按打印声明的要求添加 我不确定我是否在正确使用提供程序包

解决方法

您需要设置

Provider(create: (context) => Books())

使用Provider.of(context)的小部件上方 (通常在MaterialApp上方)

Provider(create: (context) => Books(),child: MaterialApp(

为您的Books类添加吸气剂:

  class Books with ChangeNotifier { 
   List<Book> _items = [];

   List<Book> get items => _items; 

  void addBook (Book obj) { 
  _items.add(obj); 
  notifyListeners();
  } 
}

使用Bloc包中的使用者:

Consumer.of<Books>(
builder: (context,books,child) {
return GridView.builder(
  padding: const EdgeInsets.all(10.0),itemCount: books.items.length,itemBuilder: (ctx,i) => BookItem(books.items[i]),