我想呈现一个需要HTTP调用才能获取一些数据的小部件。
我的问题是数据没有改变,仍然为空
当我放置一些日志时,我看到HTTP调用已经完成并且setState()方法被调用,但是小部件没有更新
我是新手,我来自React Native,是否有像componentWillMount这样的方法,所以在小部件之前进行HTTP调用 这是我的代码
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import './login.dart';
class Developer extends StatefulWidget {
@override
_DeveloperState createState() => _DeveloperState();
}
class _DeveloperState extends State<Developer> {
bool _isLoading = false;
SharedPreferences sharedPreferences;
void getJsonData() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
Map data = {'sale_id': sharedPreferences.getInt("token")};
var jsonResponse;
if (!_isLoading) {
setState(() {
_isLoading = true;
});
var response = await http.post(
"url",
body: json.encode(data),
headers: {
"Content-Type": "application/json",
HttpHeaders.authorizationHeader: 'Basic YnJva2VyOmJyb2tlcl8xMjM='
},
);
if (response.statusCode == 200) {
jsonResponse = json.decode(response.body);
print('jsonRespnse');
print(jsonResponse['developer_list']);
if (jsonResponse != null) {
setState(() {
data['developer_list'] = jsonResponse['developer_list'];
_isLoading = false;
});
sharedPreferences.setString("token", jsonResponse['sale_id']);
}
} else {
setState(() {
_isLoading = true;
});
print(response.body);
}
}
}
var data;
@override
void initState() {
this.getJsonData();
super.initState();
checkLoginStatus();
getJsonData();
}
checkLoginStatus() async {
sharedPreferences = await SharedPreferences.getInstance();
}
@override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xff242426),
title: Text("Developer", style: TextStyle(color: Colors.white)),
actions: <Widget>[
FlatButton(
onPressed: () {
sharedPreferences.clear();
sharedPreferences.commit();
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (BuildContext context) => LoginPage()),
(Route<dynamic> route) => false);
},
child: Text("Log Out", style: TextStyle(color: Colors.white)),
),
],
),
body: Container(
color: Colors.black,
child: _isLoading
? Center(child: CircularProgressIndicator())
: GridView.count(
crossAxisCount: 3,
children: List.generate(
data == null ? 0 : data['developer_list'].length,
(index) {
return Container(
color: Colors.black,
margin: EdgeInsets.all(10),
child: Column(
children: <Widget>[
Container(
width: double.infinity,
height: 160,
alignment: Alignment.center,
child: Image.network(
data['developer_list'][index]
['developer_image'],
width: double.infinity),
),
Container(
color: Color(0x66bbbbbb),
width: double.infinity,
height: 60,
alignment: Alignment.center,
child: Text(data['developer_list'][index]
['developer_name']),
)
],
),
);
}).toList()),
));
}
}