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;
    Key? key,
    required this.index,
    required this.matches,
    required this.results,
  }) : super(key: key);

  State<matchesRow> createState() => _matchesRowState();

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

  void initState() {

  void dispose() {

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

  Container build(BuildContext context) {
    var icon = Icons.code_sharp;
    return Container(child: Text(;

This is the function ReadPlayer()

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

    final maps = await db.query(
      columns: PlayerFields.values,
      where: '${} = ?',
      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;

  void 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