美文网首页
Flutter Widget无法刷新问题

Flutter Widget无法刷新问题

作者: 旺仔_100 | 来源:发表于2020-11-10 17:15 被阅读0次

同事使用StatefulWidget控件写界面,使用setState却无法刷新界面。看了下代码。类似于下面这种写法。
一、在MyHomePage中定义了几个变量 a,b,c

class MyHomePage extends StatefulWidget {
  String a;
  String b;
  String c;
  MyHomePage({Key key, this.title}) : super(key: key);

二、在对应的_MyHomePageState里面使用aa,bb,cc接收a,b,c 然后使用aa,bb,cc来给控件赋值。

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    String aa = widget.a;
    String bb = widget.b;
    String cc = widget.c;

    setState(() {
          aa = 235;
    });
 return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(aa),
      ),
  ....

类似于上面的代码,然后发现 setState并没有更新 Text(aa)界面数据。
先说下解决方法
1.使用UniqueKey放到对应的控件中去刷新。但是这种方式是强制刷新,不推荐。
2.界面上直接使用 widget.a来显示,不要使用局部变量缓存在去显示。原理是因为setState会去刷新widget。所以直接取widget的值会更新。使用局部缓存导致界面无法更新。

相关文章

网友评论

      本文标题:Flutter Widget无法刷新问题

      本文链接:https://www.haomeiwen.com/subject/zxmjbktx.html