Flutter:setState不更新UI

问题描述 投票:0回答:2

onTap可以打印值,但是setState不会在UI和使用有状态的小部件以及在内部构建中使用im的情况下产生任何区别,我无法知道我在哪里犯错误,而我使用的是flutter beta。

Widget build(BuildContext context) {

String text = "HEY";

void bb(){
  print('Clicked Clicked');
  setState(() {
    text = "HEY2";
  });
}

return Scaffold(
  body: Container(
      decoration: BoxDecoration(
        image:  DecorationImage(image: new AssetImage("assets/floor.jpg"), fit: BoxFit.cover,),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Center(
            child: Text(
              'HELLO, WORLD!', 
              style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold), 
              textScaleFactor: 6,),
          ),
          Divider(height: 80),
          GestureDetector(
            onTap: (){
              bb();
            },
            child: Text(text, style: TextStyle(color: Colors.red)),
          ),

        ],),
    )
);

}

flutter
2个回答
0
投票

您的变量不是页面状态的一部分,它不是构建功能的一部分。每次状态更改时,都会触发构建函数,从而变回变量text的值。

您需要移动此部分:

  String text = "HEY";

    void bb(){
      print('Clicked Clicked');
      setState(() {
        text = "HEY2";
      });
    }

到构建函数之外,变成类似这样的东西:

class _MyHomePageState extends State<MyHomePage> {
    String text = "HEY";

    void bb(){
      print('Clicked Clicked');
      setState(() {
        text = "HEY2";
      });
    }
  @override
  Widget build(BuildContext context) {

    List<bool> _selections = List.generate(3, (index) => false);


0
投票

您不应将变量放在build中。它应该在build功能之外。

class _YourPageState extends State<YourPage> {
    String text = "HEY";

    void bb() {
      print('Clicked Clicked');
      setState(() {
      text = "HEY2";
    }

    Widget build(BuildContext context) {
      ....
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.