2021-07-29

Flutter : insert data to tables in sqflite at initialaztion database

I have created helper class for sqlite database and tried to insert data to tables in intialzing database as this :

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 (club varchar(50) ,price integer ,surename varchar(3), id integer , league varchar(20))');
      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');
  }
}

now I want to display data and used it in provider ,I did this :

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

I called teams in future builder in screen :

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

I get error : The method 'getTeamsData' was called on null. Receiver: null Tried calling: getTeamsData()



from Recent Questions - Stack Overflow https://ift.tt/3ibZ9vi
https://ift.tt/eA8V8J

No comments:

Post a Comment