Flutter: Dart Convert properly null safety my class

Viewed 282

How to change my class for null safety compliant?

My error for converting my project to null safety.

  • error • The parameter 'bloc' can't have a value of 'null' because of its type, but the implicit default value is 'null' at lib/blocs/bloc_provider.dart:10:32 • (missing_default_value_for_parameter)

  • error • The parameter 'child' can't have a value of 'null' because of its type, but the implicit default value is 'null' at lib/blocs/bloc_provider.dart:10:53 •
    (missing_default_value_for_parameter)

  • error • A value of type 'BlocProvider<T>?' can't be assigned to a variable of type 'BlocProvider<T>' at lib/blocs/bloc_provider.dart:14:9 • (invalid_assignment) error • The property 'length' can't be unconditionally accessed because the receiver can be 'null' at lib/ui/login/components/sponsors_stagiaire_tab.dart:147:28 • (unchecked_use_of_nullable_value)

import 'package:flutter/cupertino.dart';

import 'blocs.dart';

class BlocProvider<T extends Bloc> extends StatefulWidget {
  final T bloc;

  final Widget child;

  BlocProvider({@required this.bloc, @required this.child});

  static T of<T extends Bloc>(BuildContext context) {
    final BlocProvider<T> _provider =
        context.findAncestorWidgetOfExactType<BlocProvider<T>>();
    return _provider.bloc;
  }

  State createState() => _BlocProviderState();
}

class _BlocProviderState extends State<BlocProvider> {
  @override
  Widget build(BuildContext context) {
    return widget.child;
  }

  @override
  void dispose() {
    widget.bloc.dispose();
    super.dispose();
  }
}
1 Answers

The 'bloc' and 'child' parameters have a null value so you need to put '?' to indicate that that value can be null.
The error "The property 'length' can't be unconditionally accessed because the receiver can be 'null' at.." warns you that you need to ensure there is a value there, to ensure this you need to use '!'. Below is an example of what I meant.

import 'package:flutter/cupertino.dart';

import 'blocs.dart';

class BlocProvider<T extends Bloc> extends StatefulWidget {
  final T? bloc;

  final Widget? child;

  BlocProvider({this.bloc, this.child});

  static T of<T extends Bloc>(BuildContext context) {
    final BlocProvider<T> _provider =
        context.findAncestorWidgetOfExactType<BlocProvider<T>>();
    return _provider.bloc;
  }

  State createState() => _BlocProviderState();
}

class _BlocProviderState extends State<BlocProvider> {
  @override
  Widget build(BuildContext context) {
    return widget.child!;
  }

  @override
  void dispose() {
    widget.bloc!.dispose();
    super.dispose();
  }
}
Related