我正在使用此应用程序,需要从API获取信息。我需要接收数据以在用户向下滚动时显示它。问题在于Stream Builder快照不接收任何数据。 我有这个课程:
页面
class BotonesPage extends StatelessWidget {
BotonesPage({Key key}) : super(key: key);
final caracteresProvider = new Provider();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
_fondoApp(),
SingleChildScrollView(
child: Column(
children: <Widget>[
_titulos(),
StreamBuilder(
stream: caracteresProvider.popularesStream,
builder: (BuildContext context, AsyncSnapshot<List> snapshot) {
if ( snapshot.hasData ) {
return CharactersVertical(
caracter: snapshot.data,
siguientePagina: caracteresProvider.getCaracteres,
);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
],
),
)
],
),
);
}
我从API获取信息的提供者。
class Provider {
final String _baseUrl = 'rickandmortyapi.com';
final String _charactersPath = '/api/character/';
bool _cargando = false;
List<Caracter> _populares = new List();
final _popularesStreamController = StreamController<List<Caracter>>.broadcast();
Function(List<Caracter>) get popularesSink => _popularesStreamController.sink.add;
Stream<List<Caracter>> get popularesStream => _popularesStreamController.stream;
void disposeStreams() {
_popularesStreamController?.close();
}
Future<List<Caracter>> _procesarRespuesta(Uri url) async {
log(url.toString());
final resp = await http.get( url );
final decodedData = json.decode(resp.body);
final caracteres = new Caracteres.fromJsonList(decodedData['results']);
return caracteres.items;
}
int _pages = 1;
Future<List<Caracter>> getCaracteres() async {
if ( _cargando ) return [];
_cargando = true;
final url = Uri.https(_baseUrl, _charactersPath, { 'page' : _pages.toString() });
_pages++;
final resp = await _procesarRespuesta(url);
_populares.addAll(resp);
popularesSink( _populares );
_cargando = false;
return resp;
}
}
小部件
class CharactersVertical extends StatelessWidget {
final List<Caracter> caracter;
final Function siguientePagina;
CharactersVertical({ @required this.caracter, @required this.siguientePagina });
final _pageController = new PageController(
initialPage: 1,
viewportFraction: 0.3
);
@override
Widget build(BuildContext context) {
final _screenSize = MediaQuery.of(context).size;
_pageController.addListener( () {
if ( _pageController.position.pixels >= _pageController.position.maxScrollExtent - 200 ){
siguientePagina();
}
});
return Container(
height: _screenSize.height * 0.2,
child: PageView.builder(
pageSnapping: false,
controller: _pageController,
itemCount: caracter.length,
itemBuilder: ( context, i ) => _crearBotonRedondeado(context, caracter[i] ),
),
);
}
...
}