[英]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.