LateError (LateInitializationError: Field 'gP1' has not been initialized.)

Can someone explain to me where I am wrong? I am programming this application and, working with sqflite, I have had this kind of problem several times when I use the readPlayer() function.

class matchesRow extends StatefulWidget {
  final List matches;
  final List results;
  final int index;
  matchesRow({
    Key? key,
    required this.index,
    required this.matches,
    required this.results,
  }) : super(key: key);

  @override
  State<matchesRow> createState() => _matchesRowState();
}

class _matchesRowState extends State<matchesRow> {
  late Player gP1;
  late Player gP2;
  bool ripescato = false;
  PlayersDatabase pb = PlayersDatabase.instance;

  @override
  void initState() {
    super.initState();
    getPlayers();
  }

  @override
  void dispose() {
    PlayersDatabase.instance.close();
    super.dispose();
  }

  Future getPlayers() async {
    List<dynamic> duel = widget.matches[widget.index];
    gP1 = await pb.readPlayer(duel[0]);
    print(gP1);
    gP2 = await pb.readPlayer(duel[0]);
    if (duel[1] == "R") {
      ripescato = true;
    } else {
      gP2 = await pb.readPlayer(duel[1]);
    }
  }

  @override
  Container build(BuildContext context) {
    var icon = Icons.code_sharp;
    return Container(child: Text(gP1.name));
  }}

This is the function ReadPlayer()

Future<Player> readPlayer(int id) async {
    final db = await instance.database;

    final maps = await db.query(
      tablePlayers,
      columns: PlayerFields.values,
      where: '${PlayerFields.id} = ?',
      whereArgs: [id],
    );

    if (maps.isNotEmpty) {
      return Player.fromJson(maps.first);
    } else {
      throw Exception('ID $id not found');
    }

I don’t understand why even if I declare the value of gP1 and gP2 in getPlayers() the error still pop up.

>Solution :

gP1 and gP2 getting from future method. It will take some time to fetch data from future method getPlayers. Use FutureBuilder or make it nullable

For nullable case it will be

    Player? gP1;
    Player? gP2;


  @override
  void initState() {
    super.initState();
    getPlayers().then((value) {
      //update Ui after getting data
      setState(() {});
    });
  }

And use case with default value on null case

Text(gP1?.name??"didnt get yet")

Leave a Reply