Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

flutter setState does not add a widget

This is my code. It is supposed to add a list tile when you enter a city in the field above and then press plus button. But it does not! There's a listView which has all the list tiles in it.The listView is supposed to show all list tiles in a list. When I press the button a message is printed to indicate the number of cities. It shows that the city is added but nothing changes in the screen. ColorfulBox is a widget that I've built. It's just a decoration.

import 'package:flutter/material.dart';
import 'package:learner/logic/Weather.dart';
import 'ColorfulBox.dart';

class CitiesScreen extends StatefulWidget{
  @override
  _CitiesScreenState createState() => _CitiesScreenState();
}
class _CitiesScreenState extends State<CitiesScreen>{
  List<Weather> weatherData = List<Weather>();
  String cityName;
  List<Widget> cities = List<Widget>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
        child: Column(
          children: <Widget>[
            DecoratedBox(
              decoration: BoxDecoration(color: Colors.blueAccent, borderRadius: BorderRadius.circular(10),
              gradient: LinearGradient(colors: [Colors.blue, Colors.purple]) ),
              child: ColorfulBox(Padding(
                padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 0),
                child: ListTile(
                  title: TextField(onChanged: (value){
                    cityName = value;
                  },
                  style: TextStyle(fontSize: 20, color: Colors.white),),
                  trailing: FlatButton(
                    child: Icon(Icons.add, size: 30, color: Colors.white,),
                    onPressed: (){
                      setState(() {
                        addCity(cityName);
                        print(cities.length);
                      });
                    },
                  ),
                ),
              ),
              )
            ),
            SizedBox(height: 30,),
            Expanded(
              child: ListView(
                shrinkWrap: true,
                scrollDirection: Axis.vertical,
                children: cities,
              ),
            )
          ],
        ),
      ),
    );
  }

  void addCity(String city){
    weatherData.add(Weather(city: city));
    Container toBeAddedCity = Container(
      margin: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
      child:  Text(city, style: TextStyle(fontSize: 22, color: Colors.white),),
    );
    cities.add(ColorfulBox(toBeAddedCity));
  }

}

Can you help me fix this? I have no idea! Is it because the addCity method is out of the build method? or it adds but does not show it?

question from:https://stackoverflow.com/questions/65914536/flutter-setstate-does-not-add-a-widget

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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,
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...