You can just use ListView.builder(...)
to create your widgets. Please do not store Widgets as states.
Sample:
class CitiesScreen extends StatefulWidget {
@override
_CitiesScreenState createState() => _CitiesScreenState();
}
class _CitiesScreenState extends State<CitiesScreen> {
final TextEditingController _controller = TextEditingController();
final List<Weather> _weatherData = <Weather>[];
final Random _rand = Random();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
child: Column(
children: <Widget>[
DecoratedBox(
decoration: const BoxDecoration(
color: Colors.blueAccent,
borderRadius: BorderRadius.all(Radius.circular(10)),
gradient: LinearGradient(
colors: <Color>[Colors.blue, Colors.purple],
),
),
child: Container(
//ColorfulBox(
color: Colors.blue,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: ListTile(
title: TextField(
controller: _controller,
style: const TextStyle(fontSize: 20, color: Colors.white),
),
trailing: FlatButton(
child: const Icon(
Icons.add,
size: 30,
color: Colors.white,
),
onPressed: () {
setState(() {
_weatherData.add(Weather(city: _controller.text));
});
_controller.clear();
},
),
),
),
),
),
const SizedBox(height: 30),
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: _weatherData.length,
itemBuilder: (_, int index) => ListTile(
tileColor: Color.fromARGB(
255,
_rand.nextInt(255),
_rand.nextInt(255),
_rand.nextInt(255),
),
title: Text(
_weatherData[index].city,
style: const TextStyle(
fontSize: 22,
color: Colors.white,
),
),
),
),
)
],
),
),
);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…