Flutter:在初始化数据库时将数据插入到 sqflite 中的表中

Flutter : insert data to tables in sqflite at initialaztion database

我已经为 sqlite 数据库创建了帮助程序 class,并尝试将数据插入到初始化数据库中的表中,如下所示:

class DbHelper {
  static final DbHelper _instance = DbHelper.internal();
  factory DbHelper() => _instance;
  DbHelper.internal();
  static Database _db;
  //---------------- Create database method-------------------
  Future<Database> createDatabase() async {
    var teamsTable = SqliteData().teams;
    var clubsTable = SqliteData().clubs;
    if (_db != null) {
      return _db;
    }
    String path = join(await getDatabasesPath(), 'clubsFantasy.db');
    _db = await openDatabase(path, version: 1,
        onCreate: (Database db, int v) async {
      await db.execute('''
          create table teams (club varchar(50) ,
          price integer ,
          surename varchar(3),
          id integer,
          league varchar(20))
          ''');
      await db.execute(
         'create table clubs (id integer ,club varchar(50) ,league_id integer,price integer ,surename varchar(3),  league_name varchar(20),counter integer , selected varchar(5))');
      teamsTable.map((e) => {db.insert('teams', e.toMap())}).toList();
      clubsTable.map((e) => {db.insert('clubs', e.toMap())}).toList();
    });

    return _db;
  }
//---------------- load data method---------------------
  Future getTeamsData() async {
    Database db = await createDatabase();
    return db.query('teams');
  }

  Future getClubsData() async {
    Database db = await createDatabase();
    return db.query('clubs');
  }
}

我在初始屏幕上调用数据库来创建数据库并将数据插入表中:

DbHelper helper;
  @override
  void initState() {
    helper = DbHelper();
    checkLogin();
    helper.createDatabase();
    super.initState();
  }

现在我想显示数据并在提供程序中使用它,我这样做了:

class TeamsProvider with ChangeNotifier {
  DbHelper helper;
  get clubs => helper.getClubsData();
  get teams => helper.getTeamsData();
}

我在屏幕上调用了 future builder 中的团队:

Widget build(BuildContext context) {
    return Consumer<TeamsProvider>(
      builder: (context, teamsProv, child) {
        return FutureBuilder(
            future: teamsProv.teams,
            builder: (context, snapshot) {
              if (snapshot.hasData) {.....etc

我收到错误: The method 'getTeamsData' was called on null. Receiver: null Tried calling: getTeamsData()

我不确定,但请尝试这样声明您的 DbHelper:

class DbHelper {
    factory DbHelper() => DbHelper._internal()
    DbHelper._internal();

DbHelper 方法如:

   static Future<Database> createDatabase() async {...
   static Future getTeamsData() async {...
   static Future getClubsData() async {...

然后:

class TeamsProvider with ChangeNotifier {
    get clubs => DbHelper.getClubsData();
    get teams => DbHelper.getTeamsData();
}