Home:ALL Converter>NoSuchMethodError: The getter 'bloc' was called on null

NoSuchMethodError: The getter 'bloc' was called on null

Ask Time:2020-01-30T16:59:36         Author:Syazwi Zaili

Json Formatter

I'm a beginner in Flutter and BLOC, i have a problem when trying to fetch Country List data.

Error was NoSuchMethodError: The getter 'bloc' was called on null.

enter image description here

below was my code. I'm just follow this tutorial https://www.youtube.com/watch?v=2DP3SEHucEk

this is Country List widget

class CountryList extends StatefulWidget {
  @override
  _CountryListState createState() => _CountryListState();
}

class _CountryListState extends State<CountryList> {
  @override
  void initState() {
    Future.delayed(Duration.zero, () async {
      final bloc = CountryRepo.of(context);
      bloc.fetchCountry();
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return CountryRepo(child: Builder(
      builder: (context) {
        final bloc = CountryRepo.of(context);

        return StreamBuilder<List<CountryModel>>(
          stream: bloc.countries,
          builder: (context, snapshot) {
            if (!snapshot.hasData)
              return Center(child: CircularProgressIndicator());
            return ListView.separated(
              shrinkWrap: true,
              itemCount: snapshot.data.length,
              itemBuilder: (BuildContext context, int index) {
                return ListTile(
                  title: Row(
                    children: <Widget>[
                      Image.asset(snapshot.data[index].flag, width: 20),
                      SizedBox(width: 10),
                      Text(
                          "${snapshot.data[index].name} (+${snapshot.data[index].callingCodes})"),
                    ],
                  ),
                  onTap: () {
                    Navigator.pop(context);
                  },
                );
              },
              separatorBuilder: (context, index) {
                return Divider();
              },
            );
          },
        );
      },
    ));
  }
}

this is Country provider

import 'package:bpg/bloc/country_block.dart';
import 'package:flutter/material.dart';

class CountryRepo extends InheritedWidget {
  final CountryBloc bloc;

  CountryRepo({Key key, Widget child})
      : bloc = CountryBloc(),
        super(key: key, child: child);

  static CountryBloc of(BuildContext context) {
    return (context.dependOnInheritedWidgetOfExactType() as CountryRepo).bloc;
  }

  bool updateShouldNotify(_) => true;
}

and this Country BLOC

import 'package:bpg/model/country_model.dart';
import 'package:rxdart/rxdart.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;

class CountryBloc {
  final _countries = BehaviorSubject<List<CountryModel>>();

  //Get Data
  Stream<List<CountryModel>> get countries => _countries.stream;

  //Set Data
  Function(List<CountryModel>) get changeCountry => _countries.sink.add;

  dispose() {
    _countries.close();
  }

  Future<void> fetchCountry() async {
    var response = await http.get("https://restcountries.eu/rest/v2/all");
    var jsonResponse = convert.jsonDecode(response.body);
    var countryJson = jsonResponse as List;
    List<CountryModel> countries = List<CountryModel>();

    countryJson
        .forEach((country) => {countries.add(CountryModel.fromJson(country))});

    changeCountry(countries);

    countries.forEach((country) => print(country.name));
  }
}

Author:Syazwi Zaili,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/59982235/nosuchmethoderror-the-getter-bloc-was-called-on-null
yy