A beginner kind of a question
as shown in below stateful widget,
I need to be able to modify in this modifiableListToPlayWith
without modifying in inputList
or this modifiableListToPlayWith
its a working code you can copy paste and test it,, this is actually surprising to me what's going wrong here?
import 'package:flutter/material.dart';
/// lets assume the input list is defined outside as ['value1','value2','value3']
class StateTest extends StatefulWidget {
final List<String> inputList;
StateTest({
@required this.inputList,
});
@override
_StateTestState createState() => _StateTestState();
}
class _StateTestState extends State<StateTest> {
List<String> originalImmutableList = new List();
List<String> modifiableListToPlayWith = new List();
@override
void initState() {
modifiableListToPlayWith = widget.inputList;
originalImmutableList = widget.inputList;
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
color: Colors.blue,
child: Column(
children: <Widget>[
GestureDetector(
onTap: (){
setState(() {
// it should add new values only to this list
modifiableListToPlayWith.add('value ${modifiableListToPlayWith.length + 1}');
});
},
child: Container(
width: 200,
height: 50,
color: Colors.amber,
margin: EdgeInsets.only(top: 40),
alignment: Alignment.center,
child: Text(
'Add',
style: TextStyle(fontSize: 20),
),
),
),
...List.generate(modifiableListToPlayWith.length, (index){
return
Text(modifiableListToPlayWith[index]);
}),
Expanded(child: Container(),),
Container(
width: MediaQuery.of(context).size.width,
child: Column(
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width,
height: 40,
color: Colors.deepOrangeAccent,
child: Text('modifiableListToPlayWith.length = ${modifiableListToPlayWith.length}'),
),
Container(
width: MediaQuery.of(context).size.width,
height: 40,
color: Colors.redAccent,
child: Text('originalImmutableList.length = ${originalImmutableList.length}'),
),
Container(
width: MediaQuery.of(context).size.width,
height: 40,
color: Colors.orangeAccent,
child: Text('widget.inputList.length = ${widget.inputList.length}'),
),
],
),
),
],
),
),
);
}
}
see how the three lists in the picture below are copies of each other while in setstate method we are only adding the new value to this 'modifiableListToPlayWith'