Flutter 无法从SharedPreference获取的数据列表

Flutter 无法从SharedPreference获取的数据列表,flutter,Flutter,当我按下按钮时,我试图保存数据列表,然后我试图访问其他屏幕中的数据。但它会引发错误 我犯了一个错误 E/flutter (17394): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: type 'List<String>' is not a subtype of type 'FutureOr<String>' E/flutter (17394): #0 SharedPrefre

当我按下按钮时,我试图保存数据列表,然后我试图访问其他屏幕中的数据。但它会引发错误

我犯了一个错误

E/flutter (17394): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: type 'List<String>' is not a subtype of type 'FutureOr<String>'
E/flutter (17394): #0      SharedPrefrence.getCartItem (package:boon/Utils/SharedPrefrence.dart:26:5)
E/flutter (17394): <asynchronous suspension>
虚拟数据嵌入

List<String> cartdatalist=['TWA Cap','₹575','M','Red'];

您需要将
getCartItem()
函数的返回类型更改为
Future
。当
prefs.getStringList(“cartkey”)
null
时,还需要返回一个空的
列表

  Future<List<String>> getCartItem() async
  {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getStringList("cartkey") ?? [];
  }
Future getCartItem()异步
{
final SharedReferences prefs=等待SharedReferences.getInstance();
返回prefs.getStringList(“cartkey”)??[];
}
然后像这样访问它

void initState() {
    super.initState();
    List<String> listdata;
    SharedPrefrence().getCartItem().then((data) {
      listdata = data;
      print(listdata);
    });
  }
void initState(){
super.initState();
列表数据;
SharedPreference().getCartItem().then((数据){
listdata=数据;
打印(列表数据);
});
}

我尝试了此操作。但当我尝试访问数据时,它会抛出类似以下错误的
未处理异常:类型“List”不是类型“Future”的子类型。
@JigarPatel@MorbiusBlack试用Future@MorbiusBlack,我已经编辑了答案以包含访问部分。谢谢你的努力,你的答案也很有效。@Johny Saini
void initState() {
    // TODO: implement initState
    super.initState();
    Future listdata = SharedPrefrence().getCartItem();
    listdata.then((data) async {
      listdata = data;
      print(listdata);
    });
  }
  Future<List<String>> getCartItem() async
  {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getStringList("cartkey") ?? [];
  }
void initState() {
    super.initState();
    List<String> listdata;
    SharedPrefrence().getCartItem().then((data) {
      listdata = data;
      print(listdata);
    });
  }
Future<List<String>> getCartItem() async
  {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getStringList("cartkey") ?? '';
}
void initState() {
  super.initState();
  SharedPrefrence().getCartItem().
  then((data) async {
  listdata = data;
  print(listdata);
});
}