【发布时间】:2020-09-18 11:18:38
【问题描述】:
编辑:Minimal reproducible example。请查看main.dart中的刷新方法。
我使用FutureBuilder 来显示网络请求的结果。我在initstate 中调用我的 fetch 方法(如建议的here):
Future<List<CheckIn>> futureCheckIn;
@override
void initState() {
super.initState();
_eventArg = Provider.of<EventArg>(context, listen: false);
_helper = ApiHelper(context);
futureCheckIn = _helper.fetchCheckIns(_eventArg.getEvent().id.toString());
}
我现在想使用RefreshIndicator 来允许用户刷新屏幕。
这很好用,直到我的网络请求以异常结束(例如 404)。通常,异常会被FutureBuilder 捕获,但在执行RefreshIndicator 中的请求后,异常未处理...
这是我的代码:
RefreshIndicator buildResult(List<CheckIn> checkIns, BuildContext context) {
return RefreshIndicator(
key: _refreshKey,
onRefresh: () async {
setState(() {});
futureCheckIn =
_helper.fetchCheckIns(_eventArg.getEvent().id.toString()); // this could end with an exception
},
child: Container(
height: MediaQuery.of(context).size.height,
child: SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
scrollDirection: Axis.vertical,
child: Column(
children: [
Container(
margin: EdgeInsets.all(10),
child: Text(
constants.CHECK_IN_SCREEN_DESCRIPTION,
style: TextStyle(fontSize: 16),
textAlign: TextAlign.justify,
),
),
ListView(
physics: NeverScrollableScrollPhysics(),
padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
scrollDirection: Axis.vertical,
shrinkWrap: true,
children: checkIns.map((el) {
return Card(
elevation: 4,
child: ListTile(
title: Text(el.name),
onTap: () async {
...
},
trailing: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.arrow_forward_ios,
color: Colors.black,
)
],
),
),
);
}).toList(),
)
],
),
),
),
);
}
如何正确使用RefreshIndicator 和FutureBuilder?
编辑@Shri Hari:抛出此异常
class AppException implements Exception {
final _message;
final _prefix;
AppException([this._message, this._prefix]);
String toString() {
return "$_prefix$_message";
}
}
class NotFoundException extends AppException {
NotFoundException([String message]) : super(message, "Data not found: ");
}
编辑@Mhark Batoctoy:是的,它是FutureBuilder的一部分:
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: futureCheckIn,
builder: (context, snapshot) {
if (snapshot.hasData) {
List<CheckIn> checkIns = snapshot.data;
return buildResult(checkIns, context); // RefreshIndicator is nested in here
} else if (snapshot.hasError) {
// Error handling
...
}
// Spinner während der Datenabfrage
return Center(
child: CircularProgressIndicator(),
);
},
);
不幸的是,将 onRefresh-Method 更改为
onRefresh: () async {
setState(() {});
futureCheckIn =
_helper.fetchCheckIns(_eventArg.getEvent().id.toString()); // this could end with an exception
},
到
onRefresh: () async {
setState(() {});
return futureCheckIn =
_helper.fetchCheckIns(_eventArg.getEvent().id.toString()); // this could end with an exception
},
或
onRefresh: () async {
setState(() {});
return _helper.fetchCheckIns(_eventArg.getEvent().id.toString()); // this could end with an exception
},
不改错误...
【问题讨论】:
-
你能发布异常吗?
标签: flutter dart networking futuretask