[英]How to use shared preferences to populate a list of string items in a stateful widget in Flutter
我想使用共享首选项来存储用户创建的文件名列表。 启动该应用程序后,我想通过从共享首选项中读取这些文件名来显示这些文件名的列表。 如何读取共享首选项数据(来自异步函数)并将数据填充到放置在有状态小部件内的 ListView 中?
class ListCard extends StatefulWidget {
const ListCard({
Key? key,
}) : super(key: key);
@override
State<ListCard> createState() => _ListCardState();
}
class _ListCardState extends State<ListCard> {
late List _dbList;
@override
void initState() {
super.initState();
_dbList = getDBNames().split(',');
}
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: _dbList.length,
itemBuilder: (BuildContext context, int index) {
return Card(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Text(
_dbList[index],
),
),
);
},
);
}
}
function 获取文件名
getDBNames() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var dbNames = prefs.getString('dbNames') ?? '';
return dbNames.split(',');
}
这给了我以下错误信息
Class 'Future<dynamic>' has no instance method 'split'.
Receiver: Instance of 'Future<dynamic>'
如何调整我的代码以使用 Future?
另外,有没有办法在应用程序启动时读取 sqlite 数据库的列表并在 ListView 中显示相同的列表?
getDBNames
是一个 Future 方法,你可以使用 FutureBuilder
class _ListCardState extends State<ListCard> {
late final future = getDBNames();
@override
Widget build(BuildContext context) {
return FutureBuilder<String?>(
future: future,
builder: (context, snapshot) {
if (snapshot.hasData) {
if (snapshot.data == null) return Text("got null data");
final _dbList = snapshot.data!.split(",");
return ListView.builder(
itemCount: _dbList.length,
itemBuilder: (BuildContext context, int index) {
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Text(
_dbList[index],
),
),
);
},
);
}
return CircularProgressIndicator();
});
}
}
查找有关FutureBuilder的更多信息。 您也可以在 sharedPreference 上保存列表
您也可以使用.then
并调用 setState 但那样看起来不太好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.