Flutter setState((){}) 无效

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class DemoWidget extends StatefulWidget {
  @override
  _DemoWidgetState createState() => _DemoWidgetState();
}

class _DemoWidgetState extends State<DemoWidget> {
  @override
  Widget build(BuildContext context) {
    var _demoText = "";

    getFromServer() async {
      var response = await http.read("http://xxx.xxx.xx.xx/xxx.json");
      setState(() {
        _demoText = response;
      });
    }

    return Scaffold(
      appBar: AppBar(
        title: Text("DemoWidgetPage"),
      ),
      body: Column(
        children: <Widget>[
          FlatButton(onPressed: getFromServer, child: Text("GetFromServer")),
          Text(_demoText),
        ],
      ),
    );
  }
}

即便点击了 GetFromServer ,下方的 Text(_demoText) 却不改变。

阅读 6.4k
2 个回答

将变量 _demoText 放在 build() 方法外面,作为类的实例变量而不是方法的实例变量。

class _DemoWidgetState extends State<DemoWidget> {
    var _demoText = "";   // <================

  @override
  Widget build(BuildContext context) {

    getFromServer() async {
      var response = await http.read("http://xxx.xxx.xx.xx/xxx.json");
      setState(() {
        _demoText = response;
      });
    }

    return Scaffold(
      appBar: AppBar(
        title: Text("DemoWidgetPage"),
      ),
      body: Column(
        children: <Widget>[
          FlatButton(onPressed: getFromServer, child: Text("GetFromServer")),
          Text(_demoText),
        ],
      ),
    );
  }
}
// response 的值打出来看看,是不是由于报错没执行下面的setState,或者值没改变
var response = await http.read("http://xxx.xxx.xx.xx/xxx.json");
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题