微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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]),

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。