在DART中创建包含列表的实例变量的副本

时间:2019-07-01 14:27:18

标签: flutter dart

我已经看到了有关此主题的一些问题,但没有找到答案。给定以下代码,我试图从一个实例到另一个实例创建“儿童”列表的副本。对于字符串,这适用于列表,但是它仅作为参考,当我在第二个实例中更新kids的值时,它也在第一个实例中更新。我的代码如下。

import 'package:flutter/material.dart';
import './screens/detail_screen.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  Person person1 = Person();
  List<Person> people = [];

  @override
  void initState() {
    super.initState();
    person1.firstName = 'Jack';
    person1.kids = [
      {'Karen': 'girl'},
      {'Bob': 'girl'}
    ];
    people.add(person1);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView.builder(
        itemCount: people.length,
        itemBuilder: (context, int index) {
          return ListTile(
            title: Text(
              '${people[index].firstName}',
            ),
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => DetailsScreen(people[index]),
                ),
              );
            },
          );
        },
      ),
    );
  }
}

class Person {
  String firstName;
  List kids;
}

class DetailsScreen extends StatefulWidget {
  final Person person;
  DetailsScreen(this.person);
  @override
  _DetailsScreenState createState() => _DetailsScreenState();
}

class _DetailsScreenState extends State<DetailsScreen> {
  static final TextEditingController _textController = TextEditingController();

  Person newPerson = Person();

  @override
  void initState() {
    super.initState();
    newPerson.firstName = widget.person.firstName;
    _textController.text = widget.person.firstName;
  }

  updateName(newName) {
    newPerson.firstName = newName;
// This is where I am trying to copy the value of "kids".
    newPerson.kids = List.from(widget.person.kids);
    newPerson.kids[1]['Bob'] = 'boy';
    print(newPerson);
    print(widget.person);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
            icon: Icon(
              Icons.close,
              color: Colors.white,
            ),
            onPressed: () {
              Navigator.pop(context);
            }),
        actions: <Widget>[
          IconButton(
              icon: Icon(
                Icons.check,
                color: Colors.white,
              ),
              onPressed: () {
                updateName(_textController.text);
              }),
        ],
      ),
      body: Center(
        child: TextField(
          controller: _textController,
        ),
      ),
    );
  }
}

有没有办法做到这一点?如果不是,最好的实践是什么来达到相同的结果?我已经阅读了这篇文章,但它是指字符串而不是列表。 How to clone (copy values) a complex object in Dart 2

2 个答案:

答案 0 :(得分:1)

您能尝试一下吗?

首先导入dart这样将页面顶部转换

seq

然后用这个更新您的updateName方法

import 'dart:convert';

答案 1 :(得分:-1)

List.from(list) 应该用于创建列表的新实例。

您可以在https://dartpad.dev/

final list = [0,1,2];
final newList = list;
print(newList);
list[0] = 55;
print(newList); //here, newList is changed because it is an instance of list

结果: [0,1,2] [55, 1, 2]

您的期望:

final list = [0,1,2];
final newList = List.from(list);
print(newList);
list[0] = 55;
print(newList); //here, newList has no change because it is a new instance

结果: [0,1,2] [0,1,2]