我想从json检索数据, 单击(形成另一个文件)后,我对所有值($ tgl,$ dokter,$ paket等)都为空,但是当我热重装(按以下代码显示)时,结果在那里并且是正确的。
我的代码有什么问题?
class DetilTreatment extends StatefulWidget{
final String nomtri;
final String jenis;
DetilTreatment(this.nomtri,this.jenis);
@override
State<StatefulWidget> createState() {
return DetilTreatmentState();
}
}
class DetilTreatmentState extends State<DetilTreatment>{
String urldest='json_detail_rawat_dart.php';
String tgl,dokter,paket,keterangan;
List tindakan,terapis;
@override
void initState() {
super.initState();
loadData();
}
void loadData() async {
final response = await http.get(remoteURL + urldest + '?nomtri=${widget.nomtri}');
if (response.statusCode == 200) {
List<dynamic> isi = jsonDecode(response.body);
tgl = isi[0]['tgl'];
dokter = isi[0]['dokter'];
paket = isi[0]['paket'];
keterangan = isi[0]['keterangan'];
} else {
throw Exception('Gagal Ambil Data Perawatan');
}
}
@override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.blue[50],
appBar: new AppBar(
title: const Text('Data Riwayat Perawatan'),
),
body: ListView(
padding: EdgeInsets.all(15.0),
children: <Widget>[
// all results are null, but when hot-reload the results displayed !
Text('Tgl/Jam : $tgl', textAlign: TextAlign.left),
Text('Nama Dokter : $dokter', textAlign: TextAlign.left),
Text('Paket : $paket', textAlign: TextAlign.left),
Text('Treatment : ', textAlign: TextAlign.left),
Text('Keterangan : $keterangan', textAlign: TextAlign.left),
],
)
);
}
}
答案 0 :(得分:1)
您需要调用setState()
来使Flutter在状态更改时重新呈现。
void loadData() async {
final response = await http.get(remoteURL + urldest + '?nomtri=${widget.nomtri}');
if (response.statusCode == 200) {
List<dynamic> isi = jsonDecode(response.body);
setState(() {
tgl = isi[0]['tgl'];
dokter = isi[0]['dokter'];
paket = isi[0]['paket'];
keterangan = isi[0]['keterangan'];
});
} else {
throw Exception('Gagal Ambil Data Perawatan');
}
}
答案 1 :(得分:0)
在您的方法内调用SetState(), 也许您会在构建过程中得到一个空错误,所以最好添加一个CircularProgressIndicator,
bool isLoading=false;
@override
void initState() {
super.initState();
loadData();
}
void loadData() async {
final response = await http.get(remoteURL + urldest + '?nomtri=${widget.nomtri}');
if (response.statusCode == 200) {
setState(() {
tgl = isi[0]['tgl'];
dokter = isi[0]['dokter'];
paket = isi[0]['paket'];
keterangan = isi[0]['keterangan'];
isLoading=true;
});
} else {
throw Exception('Gagal Ambil Data Perawatan');
}
}
Widget build(BuildContext context){
if(!isLoading)
{
return Center(child:CircularProgressIndicator());
}
else {retur Container();}