Search code examples
flutterdartdatamodel

flutter if list One of data model equal List Tow when change one changed tow


This is all the code for the screen for this question to understand the problem

import 'package:flutter/material.dart';
import 'package:pos/utils/FCIStyle.dart';
class TestScreen extends StatefulWidget {
  const TestScreen({Key? key}) : super(key: key);

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

class _TestScreenState extends State<TestScreen> {

  @override
  void initState() {
     super.initState();
     testController= TestController();
   }
late TestController testController;
   @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
          appBar: AppBar(
            backgroundColor: FCIColors.primaryColor(),
            elevation: 0,
            leading: Container(),
          ),
          body: Column(
            children: [
              Text('data 1'),
              Container(
                height: 100,
                child: Column(
                  children: List.generate(
                    testController.data1.length,
                        (index) => Text('itemCount:${testController.data1[index].itemCount}',),),
                ),
              ),
              SizedBox(height: 50),
              Text('data 2'),
              Container(
                height: 200,
                child: Column(
                  children: List.generate(
                    testController.data2.length,
                        (index) => Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('  itemCount:${testController.data2[index].itemCount}',),
                        InkWell(
                            onTap: (){
                              setState(() {
                                testController.changeStrData(index);
                              });
                            },
                            child: Icon(Icons.add_circle,size: 35,color: Colors.indigo,
                            ))
                      ],
                    )
                    ,),
                ),
              ),
            ],
          ),
        ));
  }
}

class TestController{
 final List<Data>data1=[
    Data(  itemCount: 0),
    Data( itemCount: 0),
    Data(  itemCount: 0),
  ];
   late List<Data>data2;
 TestController(){
     data2= data1;
   }
 changeStrData(index){
   data2[index].itemCount+=1;
 }
}
class Data{
  int itemCount;
  Data({ required this.itemCount});
}

The problem is equal to .

TestController(){
     data2= data1;
   }

how does the list of data model equal other?


Solution

  • The instance of Data is same here. so to create new instance .toList() isnt enough.

    The solution is create new Data from the list.

     data2 = data.map((e) => Data(itemCount: e.itemCount)).toList();
    

    You can explore Is Dart pass by reference?