gpt4 book ai didi

dart - setState 不在 Dart/Flutter 中重新加载状态?

转载 作者:IT王子 更新时间:2023-10-29 06:59:19 27 4
gpt4 key购买 nike

我遵循了 Google CodeLabs 的 Flutter 教程 -

Part 1

Part 2

然后我尝试添加 SharedPreferences持久化数据。保存数据非常有效,但删除却不行。

我的完整代码可在 https://github.com/deadcoder0904/flutter-startup-name-generator/ 获得

屏幕 1(列出所有启动名称)

flutter_heart

屏幕 2(此处显示屏幕 1 中所有已保存的启动名称)

flutter_trash

屏幕 2 上,通过单击垃圾桶图标删除启动名称不会立即删除数据。我必须遍历到 Screen 1 并在 Screen 2 再次返回才能看到被删除的项目。

错误在下面的setState或者你也可以查看on Github格式漂亮

void _pushSaved() {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (BuildContext context) {
final Iterable<ListTile> tiles = _saved.map(
(String word) {
return ListTile(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
word,
style: _biggerFont,
),
IconButton(
icon: const Icon(Icons.delete),
onPressed: () {
setState(() {
_saved.remove(word);
savePrefs(_saved);
});
},
)
],
),
);
},
);

final List<Widget> divided = ListTile.divideTiles(
context: context,
tiles: tiles,
).toList();

return Scaffold(
appBar: AppBar(
title: const Text('Saved Suggestions'),
),
body: ListView(children: divided),
);
},
),
);
}

_saved.remove(word); inside setState 不会立即删除启动名称。

我应该制作另一个有状态组件吗?我该如何解决?

最佳答案

那是因为您在构建器中创建的小部件不是Stateful

创建一个 StatefulWidget 并从 MaterialPageRoute 调用它。

只是一些变化:

void _pushSaved() {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (BuildContext context) => FavoriteList(
data: _saved, savePrefs: savePrefs, biggerFont: _biggerFont),
),
);
}

创建一个新的StatefulWidget

class FavoriteList extends StatefulWidget {
final Set<String> data;
final Function savePrefs;
final TextStyle biggerFont;
FavoriteList({Key key, this.data, this.savePrefs, this.biggerFont})
: super(key: key);

@override
_FavoriteListState createState() => _FavoriteListState();
}

class _FavoriteListState extends State<FavoriteList> {
Set<String> _saved;
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

@override
void initState() {
_saved = widget.data;
super.initState();
}

@override
Widget build(BuildContext context) {
final Iterable<ListTile> tiles = _saved.map(
(String word) {
return ListTile(
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
word,
style: widget.biggerFont,
),
IconButton(
icon: const Icon(Icons.delete),
onPressed: () {
setState(() {
_saved.remove(word);
widget.savePrefs(_saved);
});
},
)
],
),
);
},
);

final List<Widget> divided = ListTile.divideTiles(
context: context,
tiles: tiles,
).toList();

return Scaffold(
appBar: AppBar(
title: const Text('Saved Suggestions'),
),
body: ListView(children: divided),
);
}
}

关于dart - setState 不在 Dart/Flutter 中重新加载状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53845267/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com