Home > Back-end >  having some problems reading data from Supabase in flutter
having some problems reading data from Supabase in flutter

Time:07-27

im newbie with flutter, trying to build a basic Crud app with Supabase. Im trying to read some data from a table but when i debug, it shows an error on screen "unexpected null Value". Really appreciate any Help.

My model

import 'package:tdi2022_charts/models/base_model.dart';

class Equipos implements BaseModel {
  @override
  String id;
  String nombre;
  String categoria;
  int jugados;
  int ganados;
  int perdidos;
  int golesfav;
  int golescontra;
  int difgoles;

  factory Equipos.fromJson(Map<String, dynamic> json) {
    return Equipos(
      id: json['id'],
      nombre: json['name'],
      categoria: json['cat'],
      jugados: json['played'],
      ganados: json['won'],
      perdidos: json['lost'],
      golesfav: json['gf'],
      golescontra: json['ga'],
      difgoles: json['gd'],
    );
  }

  Equipos({
    required this.id,
    required this.nombre,
    required this.categoria,
    required this.jugados,
    required this.ganados,
    required this.perdidos,
    required this.golesfav,
    required this.golescontra,
    required this.difgoles,
  });

  Map toMap() {
    return {
      'name': nombre,
      'cat': categoria,
      'played': jugados,
      'won': ganados,
      'lost': perdidos,
      'gf': golesfav,
      'ga': golescontra,
      'gd': difgoles,
    };
  }

  @override
  String value() => nombre;
}

service

import 'package:tdi2022_charts/components/supabase_credential.dart';
import 'package:tdi2022_charts/models/team.dart';

class AppService extends ChangeNotifier {
  Future<void> refreshSession() async {
    if (isAuthenticated() && supabase.auth.currentSession != null) {
      final expiresAt = DateTime.fromMillisecondsSinceEpoch(
          supabase.auth.currentSession!.expiresAt! * 1000);
      if (expiresAt
          .isBefore(DateTime.now().subtract(const Duration(seconds: 2)))) {
        await supabase.auth.refreshSession();
      }
    }
  }

  Future<PostgrestResponse> getEquipos() async {
    await refreshSession();
    final response = supabase.from('Equipos').select('name').execute();
    return response;
  }}

Widget

import 'package:flutter/material.dart';
import 'package:tdi2022_charts/models/team.dart';

class Grupos extends StatelessWidget {
  final Equipos equipos;

  Grupos(this.equipos);
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      decoration: const BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: Color.fromARGB(255, 122, 120, 120),
            width: 0.5,
          ),
        ),
      ),
      child: Expanded(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('${equipos.nombre} ${equipos.categoria}'),
            const SizedBox(height: 2),
            Text('${equipos.jugados}'),
          ],
        ),
      ),
    );
  }
}

Page with Futurebuilder

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:tdi2022_charts/models/team.dart';
import 'package:tdi2022_charts/services/app_service.dart';
import 'package:tdi2022_charts/widgets/grupos.dart';

class AddTeam extends StatefulWidget {
  const AddTeam({Key? key}) : super(key: key);
  @override
  State<AddTeam> createState() => _AddTeamState();
}

class _AddTeamState extends State<AddTeam> {
  late Future<List<Equipos>> _equipos;

  Future<List<Equipos>> _getEquipos() async {
    List<Equipos> equipos =
        (await context.read<AppService>().getEquipos()) as List<Equipos>;
    return Future.value(equipos);
  }

  @override
  void initState() {
    super.initState();
    _equipos = _getEquipos();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Equipos>>(
      future: _equipos,
      builder: (ctx, snapshot) {
        List<Equipos>? equipos = snapshot.data;
        switch (snapshot.connectionState) {
          case ConnectionState.done:
            return _buildListView(equipos!);
          default:
            return _buildLoadingScreen();
        }
      },
    );
  }

  Widget _buildListView(List<Equipos> equipos) {
    return ListView.builder(
      itemBuilder: (ctx, int index) {
        return Grupos(equipos[index]);
      },
      itemCount: equipos.length,
    );
  }

  Widget _buildLoadingScreen() {
    return Center(
      child: Container(
        width: 50,
        height: 50,
        child: const CircularProgressIndicator(),
      ),
    );
  }
}

[exception caught][1] [Error!][2]

Thank you Community!!

Errors 1 [1]: https://i.stack.imgur.com/vbR9D.png

2 [2]: https://i.stack.imgur.com/tOeZW.png

CodePudding user response:

You are passing null value to FutureBuilder, use FutureBuilder as below:

   FutureBuilder<List<Equipos>>(
   future: _getEquipos(),
   builder: (ctx, snapshot) {
    List<Equipos> equipos = snapshot.data??[];
    if(!snapshot.hasData && !snapshot.hasError)
    return _buildLoadingScreen();
    
    return _buildListView(equipos);
  },
);

CodePudding user response:

In FutureBuilder Widget pass _getEquipos() method instead of _equipos to the future property.

_equipos contains a null value that is why you are getting the error

The build method will look like this

@override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Equipos>>(
      future: _getEquipos(),
      builder: (ctx, snapshot) {
        if (snapshot.hasData) {
        List<Equipos>? equipos = snapshot.data;
            return _buildListView(equipos!);
       } else {
         return _buildLoadingScreen();
       }
      },
    );
  }
  • Related