我在 Flutter 应用程序的 SharedPreference 上保存了一个字符串列表,我想在 Provider 中调用它并在小部件中使用它。 提供者:
// Increment the x::foo::z
++x::foo::z;
// Equivalent to ++(x::foo::z)
我在未来的构建器中使用了它:
get myTeam => getMyTeam();
Future<List<String>> getMyTeam() async {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
final SharedPreferences prefs = await _prefs;
return prefs.getStringList('team');
}
我收到错误:Widget build(BuildContext context) {
return Consumer<GeneralProvider>(
builder: (context, generalProvider, child) {
var items = generalProvider.myTeam;
return FutureBuilder(
future: items,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text('${items[index].club}'),
);
});
} else {
return Text('bad');
}
});
});
}
我在这里找到了许多问题的解决方案,例如: Class 'Future<dynamic>' has no instance getter 'length'
但是没有解决
答案 0 :(得分:1)
把itemCount: items.length
改成itemCount: snapshot.length
,
和未来的建设者FutureBuilder<List<String>(...etc)
。
最后会是这样:
Widget build(BuildContext context) {
return Consumer<GeneralProvider>(
builder: (context, generalProvider, child) {
var items = generalProvider.myTeam;
return FutureBuilder<List<String>>(
future: items,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.length,
itemBuilder: (context, index) {
return ListTile(
// title: Text('${items[index].club}'),//This will likely throw an error also, because items is a List<String>, there is no method called "club" for Lists.
//Replace it with this to validate:
title: Text(snapshot[index]),//This
);
});
} else {
return Text('bad');
}
});
});
}