Flutter SharedPreferences 类型 'String' 不是类型 'List<Object>' 的子类型
Flutter SharedPreferences type 'String' is not a subtype of type 'List<Object>'
我想做的是获取 SharedPreferences stringList 但出现异常。我正在尝试解决它但卡住了(我是菜鸟)。这是代码:
List<String> name;
getName() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.containsKey("name")) {
name = prefs.getStringList("name");
}
return [];
}
@override
void initState() {
this.getName();
super.initState();
}
@override
Widget build(BuildContext context) {
return name.isEmpty
? Container(
color: Colors.white,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset("assets/no-data.png"),
Text("No Seeds Saved", style: TextStyle(fontSize: 20))
],
),
),
)
: ListView.builder(
itemCount: name.length,
itemBuilder: (context, index) {
final item = name[index];
return Container(
padding: EdgeInsets.all(8),
child: Card(
color: Colors.teal[600],
child: ListTile(
title: Text(item,
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold)),
trailing: IconButton(
icon: Icon(Icons.remove_circle,
color: Colors.redAccent[400]),
onPressed: () {}),
),
),
);
},
);
}
发生异常。
_TypeError(类型 'String' 不是类型 'List' 的子类型)
构建 _BodyBuilder 时抛出了以下 _TypeError:
类型 'Future' 不是类型 'List'
的子类型
你能帮帮我吗?
我自己解决了这个问题,是因为我没有正确声明我的变量,而且我没有调用 setState 本身。这是我改变的
List<String> name = [];
getName() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.containsKey("name")) {
setState(() {
name.addAll(prefs.getStringList("name"));
});
}
}
我只是把它留在这里以防有人遇到同样的问题 xD
我想做的是获取 SharedPreferences stringList 但出现异常。我正在尝试解决它但卡住了(我是菜鸟)。这是代码:
List<String> name;
getName() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.containsKey("name")) {
name = prefs.getStringList("name");
}
return [];
}
@override
void initState() {
this.getName();
super.initState();
}
@override
Widget build(BuildContext context) {
return name.isEmpty
? Container(
color: Colors.white,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset("assets/no-data.png"),
Text("No Seeds Saved", style: TextStyle(fontSize: 20))
],
),
),
)
: ListView.builder(
itemCount: name.length,
itemBuilder: (context, index) {
final item = name[index];
return Container(
padding: EdgeInsets.all(8),
child: Card(
color: Colors.teal[600],
child: ListTile(
title: Text(item,
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold)),
trailing: IconButton(
icon: Icon(Icons.remove_circle,
color: Colors.redAccent[400]),
onPressed: () {}),
),
),
);
},
);
}
发生异常。 _TypeError(类型 'String' 不是类型 'List' 的子类型)
构建 _BodyBuilder 时抛出了以下 _TypeError: 类型 'Future' 不是类型 'List'
的子类型你能帮帮我吗?
我自己解决了这个问题,是因为我没有正确声明我的变量,而且我没有调用 setState 本身。这是我改变的
List<String> name = [];
getName() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if (prefs.containsKey("name")) {
setState(() {
name.addAll(prefs.getStringList("name"));
});
}
}
我只是把它留在这里以防有人遇到同样的问题 xD