flutter - Flutter State 值更新父值(?)
问题描述
我正面临着 Flutter 的新情况,我不明白。我有以下情况。使用 await Navigator.of(context).push( MaterialPageRoute() 将帖子类值传递到新窗口以修改帖子值;我复制此值以便获得临时值(以防取消修改)
使用 setState,我更新了 newPost 值,我刚刚意识到它也更新了原始 Post。Witch 质疑我对 Flutter 中状态值的理解。
举个例子 :
class EditPost extends StatefulWidget {
final MyPostModel post;
EditPost({
Key key,
@required this.post,
}) : super(key: key);
static Future<void> show(BuildContext context,
{Database database, UserModel user, MyPostModel post}) async {
//get the context form the BuildContext of parent controller
await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => EditPost(
post: post,
),
fullscreenDialog: true,
),
);
}
@override
_EditPostState createState() => _EditPostState();
}
class _EditPostState extends State<EditPost> {
MyPostModel newPost;
@override
void initState() {
newPost = widget.post;
}
@override
Widget build(BuildContext context) {
return Theme(
data: ThemeData(
primarySwatch: Colors.deepPurple,
colorScheme: ColorScheme.light(primary: Colors.deepPurple)),
child: Scaffold(
appBar: AppBar(title: Text('modify post title')),
body: TextButton(child(Text('tst'), onTap((){setState((){newPost.title='mod';})})),)));}
在调试视图中,newPost.title 获得了正确的“mod”值,但 post.title 也被更改(为“mod”)。我错过了什么?
解决方案
推荐阅读
- python - Keras 分子活动模型
- javascript - 映射并返回已解析的承诺数组的函数的名称?
- python - 尝试发送 Elasticsearch 时不可散列的类型“dict”
- python - 面试评估。难以理解挑战
- java - 如何将 GraphQL 嵌入现有的 REST 后端
- python - 如何只显示最后六个单词
- javascript - 为什么即使在设置“esponse.addHeader("Access-Control-Allow-Origin", "*");" 之后 CORS 请求也会失败 在小服务程序中?
- regex - 正则表达式必须包含子字符串
- java - 无法编辑其他 Parse User 对象,在后台保存不会写入 Parse Dashboard
- qt - 使用 Qt 创建器在 MainWindow.ui 上使用多个表单