【问题标题】:Flutter: Remove item for a list reflect another listFlutter:删除列表的项目反映另一个列表
【发布时间】:2021-09-12 12:18:05
【问题描述】:

我有以下颤振代码, 我有一个列表,我们称之为list1,我正在将这个列表的值对应到另一个列表list2

当我从list1 中删除一个元素时,它会自动从list2 中删除!

有一个最少的代码可以重现该问题。 我无法理解这种奇怪的行为,谁能给我解释一下?

我想要做的是删除一个项目表单 list1 但保持 list2 原样。

这是代码:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

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

class EmptyFile extends StatefulWidget {
  final list1 = ["1", "2", "3"];
  EmptyFile({Key? key}) : super(key: key);
  @override
  _EmptyFileState createState() => _EmptyFileState(list1);
}

class _EmptyFileState extends State<EmptyFile> {
  List<String> list1 ;
  List<String> list2 = [];

  _EmptyFileState(this.list1) {
    list2 = list1;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
            appBar: AppBar(
              title: const Text('Example App'),
            ),
            body:
            Container(
              child: RaisedButton(
                onPressed: () {
                  print("list1.last ${list1.last}"); // the result is: list1.last 3
                  list2.remove("3");                 // here I delete from list2 (list TWO)
                  print("list1.last ${list1.last}"); // the result is: list1.last 2 . Here an item from list ONE has been deleted!!!
                },
                child: Text('delete last Item'),
              ),
            )
        ));
  }
}


您可以从这里在线运行代码:https://dartpad.dev/81d0a66ac7c46258df7847fdc7a10e96?null_safety=true

【问题讨论】:

    标签: list flutter dart


    【解决方案1】:

    由此

    list2 = list1;
    

    您实际上并没有复制list1。分配给list2 的列表也是相同的。

    所以你需要改成这个。

    list2 = [...list1];
    

    【讨论】:

      【解决方案2】:

      显然,通过引用复制列表。 因此,要将列表的值复制到另一个列表,请使用以下代码:

      list2  = List.from(list1);
      

      代替:

      list2 = list1;
      

      【讨论】:

        【解决方案3】:

        你可以使用传播操作:

        list2 = [...list1];
        

        这应该允许任何可迭代对象复制值而不是使用引用。

        【讨论】:

          猜你喜欢
          • 2011-02-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-23
          • 2019-06-06
          相关资源
          最近更新 更多