Flutter:setState() 工作,但不重新渲染

标签 flutter dart state setstate state-management

我正在通过制作一个小新闻应用来学习 Flutter。每个选项卡都有一个新闻文章小部件列表,其中包含图像、标题、描述、“了解更多”链接按钮以及用于扩展或缩小小部件以包含或隐藏描述的按钮。

我现在的问题是扩展部分。当我按下按钮展开小部件时,setState() 被调用并且我的 bool 值 _expanded 被切换。但是,我认为它不会被重新渲染,因为小部件不会展开。正如您将在我的代码中看到的那样,我有一个内联条件作为列表中的小部件,形式为 _expanded ?展开时的选项:未展开时的选项。我已经通过在内联条件前面放置一个 ! 来验证这些小部件是我想要的,并且它们显示了它们应该显示的内容,所以我很困惑。

目前我唯一的想法是,它可能与状态不可变这一事实有关,也许我正在尝试更改状态而不是替换和重新渲染。有任何想法吗?谢谢!

我试图只包含必要的内容,但这里是一些代码:

class NewsList extends StatefulWidget {
  NewsList({this.keyword});
  final String keyword;

  @override
  createState() => NewsListState(keyword: keyword);
}

class NewsListState extends State<NewsList> {
  NewsListState({this.imageURLs, this.titles, this.texts, this.keyword});
  final List<String> imageURLs;
  final List<String> titles;
  final List<String> texts;
  final String keyword;

  List<NewsArticle> _newsArticles = List<NewsArticle>();

  @override
  void initState() {
    super.initState();
    _populateNewsArticles();
  }

  @override
  void dispose() {
    super.dispose();
  }

  void _populateNewsArticles() {
    WebService().load(NewsArticle().all(keyword)).then((newsArticles) => {
          setState(() {
            _newsArticles = newsArticles;
          })
        });
  }

  Widget _buildNewsArticles(BuildContext build, int index) {
    bool _expanded = false;
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(const Radius.circular(10)),
          color: Colors.white,
          boxShadow: [
            BoxShadow(
                color: Colors.grey[300],
                blurRadius: 20,
                spreadRadius: 3,
                offset: Offset(5, 5))
          ]),
      child: Column(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                _newsArticles[index].urlToImage == null
                    ? AssetImage(Constants.NEWS_PLACEHOLDER_IMAGE_ASSET_URL)
                    : CachedNetworkImage(
                        imageUrl: _newsArticles[index].urlToImage),
                Padding(padding: const EdgeInsets.symmetric(vertical: 5)),
                Text(
                  _newsArticles[index].title,
                  textAlign: TextAlign.left,
                  style: TextStyle(
                    fontSize: 25,
                    fontWeight: FontWeight.w700,
                    height: 0.8,
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(4, 15, 4, 0),
                  child: Platform.isIOS
                      ? CupertinoButton.filled(
                          child: Text(
                            "Learn More",
                            style: TextStyle(fontSize: 17),
                          ),
                          onPressed: () =>
                              navigateToUrl(_newsArticles[index].url),
                          pressedOpacity: 0.6,
                        )
                      : RaisedButton(
                          onPressed: () =>
                              navigateToUrl(_newsArticles[index].url),
                          color: Color.fromRGBO(0, 122, 255, 1.0),
                          animationDuration: Duration(milliseconds: 1000),
                          child: Text(
                            "Learn More",
                            style: TextStyle(fontSize: 16, color: Colors.white),
                          ),
                        ),
                ),
                !_expanded ? Text("test description") : Container(),
                !_expanded
                    ? IconButton(
                        icon: Icon(Icons.keyboard_arrow_up),
                        onPressed: () => setState(() {
                          _expanded = !_expanded;
                        }),
                      )
                    : IconButton(
                        icon: Icon(Icons.keyboard_arrow_down),
                        onPressed: () {
                          setState(() {
                            debugPrint(_expanded.toString());
                            _expanded = !_expanded;
                            debugPrint(_expanded.toString());
                          });
                        },
                      ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget build(BuildContext context) {
    return ListView.separated(
      separatorBuilder: (BuildContext context, int index) =>
          Padding(padding: const EdgeInsets.symmetric(vertical: 15)),
      padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 30),
      itemBuilder: _buildNewsArticles,
      itemCount: _newsArticles.length,
    );
  }
}

最佳答案

_expanded 是在 buildNewsArticles 方法中定义和初始化的局部变量。因此,每次 buildNewsArticles 运行时,_expanded 都被初始化为 false。

您应该将 _expanded 移出该方法,使其成为 NewsListState 的成员变量。

关于Flutter:setState() 工作,但不重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57949146/

相关文章:

flutter - 无法在列中设置 GridView

java - 在请求之间用 spring 保持状态

flutter 图标作为背景并溢出

firebase - 无法将类型 'Future<String>' 的值分配给类型 'String' 的变量

flutter - 如何在 Flutter DataColumn 小部件中将标签居中?

javascript - 更新嵌套在对象内的数组的状态(ReactJS)

javascript - 如何使用正确的 isLoading 属性创建默认的 Vuex 状态

dart - 如何在 StatelessWidget 中更改 StatefulWidget 的状态?

soap - 如何在 Dart 上生成摘要密码以与 ip camera 通信

generics - 在 Dart 中,子类如何扩展父类(super class),让子类的泛型类型扩展父类(super class)的类型?