Home > Net >  type 'Null' is not a subtype of 'String' in flutter, firebase
type 'Null' is not a subtype of 'String' in flutter, firebase

Time:11-24

I want to display tatausaha data but every time I log in I get an error message "type null is not a subtype of type string", even though I use strings in my model and in firebase. can anyone help me?

this is my home_page.dart

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    context.read<TataUsahaCubit>().fetchTataUsaha();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Widget header() {
      return BlocBuilder<AuthCubit, AuthState>(
        builder: (context, state) {
          if (state is AuthSuccess) {
            return Container(
              margin: EdgeInsets.only(
                  right: defaultMargin, left: defaultMargin, top: 30),
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Hay,\n${state.user.name}',
                          style: blackTextStyle.copyWith(
                            fontSize: 24,
                            fontWeight: semiBold,
                          ),
                          overflow: TextOverflow.ellipsis,
                        ),
                        Text(
                          'Ingin Melihat Guru kamu?',
                          style: greyTextStyle.copyWith(
                            fontSize: 16,
                            fontWeight: light,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          } else {
            return SizedBox();
          }
        },
      );
    }

    Widget kepalaSekolah() {
      return Container(
        margin: EdgeInsets.only(
          left: defaultMargin,
          right: defaultMargin,
          top: 30,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Kepala Sekolah',
              style: blackTextStyle.copyWith(
                fontSize: 18,
                fontWeight: semiBold,
              ),
            ),
            KepalaSekolahTile(
              name: 'Charles Marsel Palasa, S.Pd.',
              imageUrl: 'assets/kepala_sekolah.jpeg',
              jabatan: 'Kepala Sekolah',
            ),
          ],
        ),
      );
    }

    Widget tataUsaha(List<TataUsahaModel> tatausahah) {
      return Container(
        margin: EdgeInsets.only(
          left: defaultMargin,
          right: defaultMargin,
          top: 20,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Tata Usaha',
              style: blackTextStyle.copyWith(
                fontSize: 18,
                fontWeight: semiBold,
              ),
            ),
            Column(
              children: tatausahah.map((TataUsahaModel tatausaha) {
                return TataUsahaTile(tatausaha);
              }).toList(),
            ),
          ],
        ),
      );
    }

    return BlocConsumer<TataUsahaCubit, TataUsahaState>(
        listener: (context, state) {
      if (state is TataUsahaFailed) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            backgroundColor: kRedColor,
            content: Text(state.error),
          ),
        );
      }
    }, builder: (context, state) {
      if (state is TataUsahaSuccess) {
        return ListView(
          children: [
            header(),
            kepalaSekolah(),
            tataUsaha(state.tatausahah),
          ],
        );
      }
      return Center(
        child: CircularProgressIndicator(
          color: kPrimaryColor,
        ),
      );
    });
  }
}

tata_usaha_cubit.dart

part 'tata_usaha_state.dart';

class TataUsahaCubit extends Cubit<TataUsahaState> {
  TataUsahaCubit() : super(TataUsahaInitial());
  void fetchTataUsaha() async {
    try {
      emit(TataUsahaLoading());

      List<TataUsahaModel> tatausahah =
          await TataUsahaService().fetchTataUsaha();
      emit(TataUsahaSuccess(tatausahah));
    } catch (e) {
      emit(TataUsahaFailed(e.toString()));
    }
  }
}

tata_usaha_state.dart

part of 'tata_usaha_cubit.dart';

abstract class TataUsahaState extends Equatable {
  const TataUsahaState();

  @override
  List<Object> get props => [];
}

class TataUsahaInitial extends TataUsahaState {}

class TataUsahaLoading extends TataUsahaState {}

class TataUsahaSuccess extends TataUsahaState {
  final List<TataUsahaModel> tatausahah;
  TataUsahaSuccess(this.tatausahah);
  @override
  List<Object> get props => [tatausahah];
}

class TataUsahaFailed extends TataUsahaState {
  final String error;
  TataUsahaFailed(this.error);
  @override
  List<Object> get props => [error];
}

tata_usaha_model.dart

import 'package:equatable/equatable.dart';

class TataUsahaModel extends Equatable {
  final String id;
  final String name;
  final String tahunMasuk;
  final String posisi;
  final String quotes;
  final String imageUrl;

  TataUsahaModel({
    required this.id,
    this.name = '',
    this.tahunMasuk = '',
    this.posisi = '',
    this.quotes = '',
    this.imageUrl = '',
  });

  factory TataUsahaModel.fromJson(String id, Map<String, dynamic> json) =>
      TataUsahaModel(
        id: id,
        name: json['name'],
        tahunMasuk: json['tahunMasuk'],
        posisi: json['posisi'],
        quotes: json['qoutes'],
        imageUrl: json['imageUrl'],
      );

  Map<String, dynamic> toJson() => {
        'id': id,
        'name': name,
        'tahunMasuk': tahunMasuk,
        'posisi': posisi,
        'quotes': quotes,
        'imageUrl': imageUrl,
      };

  @override
  List<Object?> get props => [
        id,
        name,
        tahunMasuk,
        posisi,
        quotes,
        imageUrl,
      ];
}

tata_usaha_service.dart

class TataUsahaService {
  CollectionReference _tatausahaRef =
      FirebaseFirestore.instance.collection('tatausaha');

  Future<List<TataUsahaModel>> fetchTataUsaha() async {
    try {
      QuerySnapshot result = await _tatausahaRef.get();

      List<TataUsahaModel> tatausaha = result.docs.map((e) {
        return TataUsahaModel.fromJson(e.id, e.data() as Map<String, dynamic>);
      }).toList();
      print(tatausaha);
      return tatausaha;
    } catch (e) {
      throw e;
    }
  }
}

CodePudding user response:

Please check your error message when building the app.

I don't know exactly where but, there is trying to parse String from null.

I guess the below part is the problem. (Not sure)

Text(
   'Hay,\n${state.user.name}',

Print the 'state.user.name' before you use it.

And make if condition to avoid it.

CodePudding user response:

You have to null safety. For example, you declare name is String then

name: json['name'] ?? ''; // default if null name will be set to empty

on another way: declare variable name as String? // ? means can be null.

or more carefully

name: (json['name'] ?? '').toString();
// eventhough server/firebase return wrong type such as Bool not String, your code will not be through exception wrong type casting.
  • Related