我是 Flutter 和 BLOC 的初学者,在尝试获取国家/地区列表数据时遇到问题。
错误是NoSuchMethodError:在 null 上调用了 getter 'bloc'。
下面是我的代码。我只是按照本教程https://www.youtube.com/watch?v=2DP3SEHucEk
这是国家列表小部件
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();
},
);
},
);
},
));
}
}
这是国家供应商
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;
}
和这个国家集团
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));
}
}