2

我有一个脚手架,其中 AppBar 我有一个 IconButton,我想像开关一样工作:它在按下时会改变其状态。

尽管使用 bool 和 setState 很容易实现,但整个小部件在 setState 上重绘,如下所示:

actions: <Widget>[
    IconButton(icon:Icon(Icons.favorite, 
        color: estaMarcada ? K.color_highlight : K.color_background),
        onPressed: () { setState(() 
            {estaMarcada = not estaMarcada;});},
     ),

我只想重绘图标(或 AppBar),而不是整个 Scaffold。

有任何想法吗?

提前致谢。

4

3 回答 3

3

将您的 AppBar 提取到单独的StatefulWidgetsetState()在其中

class MyAppBar extends StatefulWidget {

  MyAppBar() : super();

  @override
  _MyAppBarState createState() => _MyAppBarState();
}

class _MyAppBarState extends State<MyAppBar> {
  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: Row(
        children: <Widget> [
          Icon(K.icon),
          Text(K.title), 
        ]),
      actions: <Widget>[
        IconButton(
          icon:Icon(Icons.favorite, 
            color: appData.getMark() ? K.color_highlight : K.color_background),
          onPressed: () { 
            setState(() {
              appData.setMark();
            });
          },
        ),
      ]
    );
  }
}
于 2019-06-17T15:22:55.687 回答
2

我怀疑你的脚手架的 build() 方法有副作用或进行网络调用。您应该始终构建您的 build() 方法,就好像它们可能每秒被调用 60 次一样,因此它们应该是快速且幂等的。

于 2019-06-18T02:38:17.763 回答
1

感谢@DivinePaul,我做到了:

class MyAppBar extends StatefulWidget {

  MyAppBar() : super();

  @override
  _MyAppBarState createState() => _MyAppBarState();
}

class _MyAppBarState extends State<MyAppBar> {
  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: Row(
        children: <Widget> [
          Icon(K.icon),
          Text(K.title), 
        ]),
      actions: <Widget>[
        IconButton(
          icon:Icon(Icons.favorite, 
            color: appData.getMark() ? K.color_highlight : K.color_background),
          onPressed: () { 
            setState(() {
              appData.setMark();
            });
          },
        ),
      ]
    );
  }
}
于 2019-06-19T03:00:46.370 回答