0

我是Hiveflutter数据库的新手,我想弄清楚为什么我不能Hive.openBox在里面使用FutureBuilder

FutureBuilder(
  future: Hive.openBox<User>('userBox'),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      final User userAccount = snapshot.data;
      if (userAccount == null) {
        return Center(
            child: Container(
          child: Text('LOGIN'),
        ));
      } else {
        return Center(
            child: Container(
          child: Text('SUCCESS'),
        ));
      }
    }
    return Container(
      width: 0.0,
      height: 0.0,
    );
  },
);

我收到此错误:

type 'BoxImpl' is not a subtype of type 'User'

但是这段代码在main功能上工作正常:

var box =  await Hive.openBox<User>('userBox');

User班级:

@HiveType(typeId: 1)
class User{
  @HiveField(0)
  String username;
  @HiveField(1)
  String password;
  @HiveField(2)
  String mobileNumber;
  @HiveField(3)
  String biography;
  @HiveField(4)
  String avatar;
  @HiveField(5)
  String website;
  @HiveField(6)
  String linkedinLink;
  @HiveField(7)
  String githubLink;
  @HiveField(8)
  String facebookLink;
  @HiveField(9)
  String telegramLink;
  @HiveField(10)
  String twitterLink;
  @HiveField(11)
  PageInfo pageInfo;

  User(this.username, this.password, this.mobileNumber, this.biography, this.avatar, this.website, this.linkedinLink, this.githubLink,
      this.facebookLink, this.telegramLink, this.twitterLink, this.pageInfo);
}

main.dart

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  var appDocumentDirectory = await path_provider.getApplicationDocumentsDirectory();

  Hive
    ..init(appDocumentDirectory.path)
    ..registerAdapter(UserAdapter())
    ..registerAdapter(PageInfoAdapter());

  runApp(MultiProvider(providers: providers, child: OKToast(child: StartupApplication())));
}
4

2 回答 2

1

问题已解决,这是在里面投射用户FutureBuilder

builder: (context, AsyncSnapshot<Box<User>> snapshot) {
  if (snapshot.connectionState == ConnectionState.done) {
    final Box<User> userAccount = snapshot.data;
    if (userAccount.isEmpty) {
      return Center(
          child: Container(
            child: Text('LOGIN',style: TextStyle(color: Colors.white),),
          ));
    } else {
      return Center(
          child: Container(
            child: Text('SUCCESS',style: TextStyle(color: Colors.white),),
          ));
    }
  }
  return Container(
    width: 0.0,
    height: 0.0,
  );
},
于 2020-03-16T19:15:26.037 回答
0

替换这个

..init(appDocumentDirectory.path)

..initFlutter(appDocumentDirectory.path);

于 2020-03-16T19:03:03.937 回答