I have a problem in flutter when I add a new element to the list and I call setState
, the list is updated but the screen is not.
I tried calling the setState
after addText()
but it doesn’t work also.
This is my code:
import 'package:flutter/material.dart';
class TestScreen extends StatefulWidget {
@override
_TestScreenState createState() => _TestScreenState();
}
class _TestScreenState extends State<TestScreen> {
List<Widget> testList = [
Text('data'),
];
void addText() {
setState(() {
testList.add(
Text('data'),
);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: true,
body: SafeArea(
child: Column(
children: [
Expanded(
child: ListView(
children: testList,
),
),
ElevatedButton(
onPressed: () {
setState(() {
addText();
});
},
child: Text('Click'))
],
),
),
);
}
}
2
Answers
You can use
listView
like thisYour bug is because of calling
setState
twice, there is no need to call it inaddText()
:happy coding…