K.k
K.k

Reputation: 489

flutter: Variable can't be used as a setter because it's final

List<TestModel> lists = List();

FutureBuilder<List<TestModel>>(
          future: testNetworkRepository.fetchAlltext(TestModel.testKey),
          builder: (context, snapshot){
            if(snapshot.hasData){
              lists = snapshot.data;
              return Contanier();
            }
          }
)

Future _editText(int index, String testKey) async {
    await showDialog(
        context: context,
        child: SimpleDialog(
          children: [
            SimpleDialogOption(
              child: TextButton(
                    child: Text("Edit"),
                    onPressed: (){
                      setState(() {
                        lists[index].text = editTextController.text; <- error occured
                      });
                    },
                  ),
            )
          ],
        )
    );
  }

This is my code. I want to edit lists[index].text.

But error occured.

'text' can't be used as a setter because it's final.

How can I solve this problem?

Upvotes: 4

Views: 18140

Answers (3)

dosytres
dosytres

Reputation: 2286

State parameters are immutable, but what you can do is to call it with the copyWith() method. The copyWith() method, returns a new State. It means that we cannot change the state but make the changes to the current one and assign it to a new one. with every change a new state will be returned.

Upvotes: 1

Muhammad Nawaz
Muhammad Nawaz

Reputation: 11

Go in data class model change it like below:

static late List<item> items

if they not working then remove final keyword.

Upvotes: 1

biniyam112
biniyam112

Reputation: 1182

This error happened because the text property of the TestModel class is final. Final objects arent meant to be changed in Flutter. to fix this problem you should go to the TestModel class and remove final from the text property.

Upvotes: 5

Related Questions