flutter - 有没有更好的异步加载数据到 CupertinoPicker 的方法?
问题描述
有没有更好的异步按需加载数据到 CupertinoPicker 的方法?
我基本上做的是监听滚动事件并检测 CupertinoPicker 是否滚动到开始之外,并在加载“数据”期间显示一个微调器。我将微调器插入从数据构建的小部件列表中,并在将新小部件添加到列表中时将其删除。
我不能说是什么让我想知道是否有更好的方法,但我觉得应该有更好的方法来解决这个问题。
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Widget> items = [Divider(color: Colors.red)];
bool refreshInProgress = false;
loadMoreData() {
if(refreshInProgress) return;
setState(() {
refreshInProgress = true;
});
items.insert(0, FutureBuilder(
future: Future.delayed(Duration(seconds: 2)).then((value) {
var newItems = [Text("A"), Text("B"), Text("C")];
setState((){
items = [...newItems, ...items.where((w) => !(w is FutureBuilder) || w == null)];
refreshInProgress = false;
});
return newItems;
}),
builder: (context, snapshot) {
if(snapshot.connectionState == ConnectionState.waiting) return Center(child: CircularProgressIndicator());
return null;
},
));
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(child: Container(
margin: EdgeInsets.all(20),
child: Column(children: [
Expanded(flex: 4, child: NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification notification) {
if ((notification is ScrollEndNotification) && notification.metrics.pixels <= 0) {
loadMoreData();
return true;
}
return false;
},
child: CupertinoPicker.builder(
itemExtent: 32,
itemBuilder: (BuildContext context, int index) {
if(index >= 0 && index < items.length) return Center(child: items[index]);
return null;
},
onSelectedItemChanged: (int value) {
print("onSelectedItemChanged: $value");
},
))
),
Expanded(child: Container(child: Text("$items"))),
Row(children: [
RaisedButton(onPressed: () => setState(() => loadMoreData()), child: Text("Load more data")),
])
],
)),
)),
);
}
}
解决方案
推荐阅读
- javascript - JS - Document.Write 问题
- python - 我想使用列表理解来创建一个数组,上面写着 Patient 0、Patient 1 等
- python - 如何在熊猫中获取部分和完整字符串匹配组合的行?
- ruby-on-rails - 为什么 Rails 服务器无法在 Windows 10 上运行
- javascript - Sinon 存根返回先前测试用例的模拟值
- php - 如何在控制器中使用whereNotNull,同时使用('多对多关系')在刀片视图上显示?
- netty - io.netty.util.internal.bestAvailableMac 在具有复杂网络的系统上
- ruby-on-rails-5 - 更新元数据时 .heic 格式的 Rails Active 存储“识别 -format %[orientation]”问题
- sql - 如何从 NESTED 字段中的 ARRAY 中删除 STRUCT
- python - 将查询字符串参数传递给请求调用不起作用