首页 > 解决方案 > 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”)。我错过了什么?

标签: flutterdartstate-management

解决方案


推荐阅读