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)
却不改变。
将变量 _demoText 放在 build() 方法外面,作为类的实例变量而不是方法的实例变量。