我有一个需要拉动刷新功能的应用程序,因此我将 StreamBuilder窗口小部件放置在 RefreshIndicator窗口小部件中,但是我不知道如何手动刷新触发 onRefreshed 事件时,将其添加到StreamBuilder。
答案 0 :(得分:1)
将stream
作为state variable
并在上拉刷新时重置将解决此问题。
在下面的代码中,我将在按下按钮时重置流。希望对您有帮助。
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new _MyAppState();
}
}
class _MyAppState extends State<MyApp> {
var stream; // state variable
@override
void initState() {
super.initState();
stream = newStream(); // initial stream
}
Stream<String> newStream() =>
Stream.periodic(Duration(seconds: 1), (i) => "$i");
@override
Widget build(BuildContext context) {
var streamBuilder = StreamBuilder(
initialData: "0",
stream: stream,
builder: (context, snapshot) {
return new Text(snapshot.data);
});
return MaterialApp(
title: 'Trial',
home: Scaffold(
appBar: AppBar(title: Text('Stream builder')),
body: Column(
children: <Widget>[
streamBuilder,
FlatButton(
onPressed: () {
setState(() {
stream = newStream(); //refresh/reset the stream
});
},
child: Text("Reset"))
],
)));
}
}
答案 1 :(得分:0)
可以使用RefreshIndicatorState。show方法轻松完成此操作:
class _MyAppState extends State<MyApp> {
final refreshIndicatorKey = GlobalKey<RefreshIndicatorState>();
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Trial',
home: Scaffold(
appBar: AppBar(title: Text('Stream builder')),
body: Column(
children: <Widget>[
StreamBuilder(
stream: <stream>, // Stream is here
builder: (context, snapshot) {
return
RefreshIndicator(
key: refreshIndicatorKey, // Specify a key declared above!
onRefresh() => <future> // Refresh callback is here
child: ListView.builder(...), // List view is built here
);
},
),
FlatButton(
child: Text('Reload'),
onPressed: () {
// Show refresh indicator and run refresh callback
refreshIndicatorKey.currentState.show();
}
),
],
),
);
}
}
}