Mr Jax
Mr Jax

Reputation: 1017

Flutter: The method 'listenable' isn't defined for the type 'Box' (using Hive)

I'm trying to read the contents of a Box using Hive, following this SO comment, but I get the following error:

The method 'listenable' isn't defined for the type 'Box'

The code in question is:

FutureBuilder(
      future: Hive.openBox<Contact>('testBox'),
      builder: (context, snapshot) {
        return ValueListenableBuilder(
          valueListenable: Hive.box<Contact>('contacts').listenable(),
          builder: (context, Box<Contact> box, _) {
            if (box.values.isEmpty) {
              return Text('data is empty');
            } else {
              return ListView.builder(
                itemCount: box.values.length,
                itemBuilder: (context, index) {
                  var contact = box.getAt(index);
                  return ListTile(
                    title: Text(contact.name),
                    subtitle: Text(contact.age.toString()),
                  );
                },
              );
            }
          },
        );
      },
    ),

pubspec.yaml:

hive: ^1.4.1+1
hive_flutter:
  git:
    url: git://github.com/hivedb/hive.git
    path: hive_flutter

What I am trying to do is list the content of the box when the screen loads. I can't seem to figure out where I am going wrong - any guidance would be greatly appreciated!

Upvotes: 14

Views: 6242

Answers (3)

RuslanBek
RuslanBek

Reputation: 2009

After using @MrJax's answer, if you get error like: 'The method 'listenable' isn't defined for the type 'Box' , you should import both hive packages:

import 'package:hive_flutter/hive_flutter.dart';
import 'package:hive/hive.dart';

and assign Box type for ValueListenableBuilder widget like this: ValueListenableBuilder<Box<Contact>>

Upvotes: 1

Pro Co
Pro Co

Reputation: 371

Get the Most Upgraded Version of Hive, (currently it is) hive: ^2.0.4 Get the Most Upgraded Version of Hive_Flutter (currently) hive_flutter: ^1.0.0

In your Working Space Kindly Import them all

import 'package:hive_flutter/hive_flutter.dart';
import 'package:hive/hive.dart';

And You are good to Go to use, Box, Value-Listenable, Builder... etc.

Upvotes: 2

Mr Jax
Mr Jax

Reputation: 1017

The solution: hive_flutter.dart needs to be imported first

import 'package:hive_flutter/hive_flutter.dart';

Upvotes: 38

Related Questions