仅在从API中快速重载后才检索值

时间:2020-08-09 17:12:34

标签: flutter

我有点扑朔迷离,我一直在使用rest API作为后端来构建应用程序,每当我尝试从GET API加载要显示在首页屏幕上的数据时,我都无法获取该值从登录屏幕推送和替换后,重新加载或刷新应用程序上的小部件。请帮我!!!已经一个星期了,我仍然停留在那些错误上。

我的代码:

class HomePage extends StatefulWidget{

  final String name;
  HomePage(this.name);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>{

  String token;

  void iniState() {
    super.initState();
    GetRequest().getUserName(token);
  }
  
  Widget build(BuildContext context){
    return Scaffold(
      body: Container(
        alignment: Alignment.topCenter,
        child: SafeArea(
          child: bodyPage(context),
        ),
      ),  
    );   
  }
}

Widget bodyPage(BuildContext context) {
  
  return Scaffold(
    body: SafeArea(
      child: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 20.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              SizedBox(height: 15),
              _appBar(context),
            ],
          ),
        ),
      ),
    ),
  );
}

  _appBar(context) {

    String myName = mData.fullname;

    return Row(
      children: <Widget>[
        CircleAvatar(
          backgroundImage: NetworkImage(
              "https://jshopping.in/images/detailed/591/ibboll-Fashion-Mens-Optical-Glasses-Frames-Classic-Square-Wrap-Frame-Luxury-Brand-Men-Clear-Eyeglasses-Frame.jpg"),
        ),
        SizedBox(width: 15),
        Text("Hello, ", 
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 18,
          ),
        ),
        Text( 
          myName ?? 'KOOMPI',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: Colors.blueAccent)),
      ],
    );
  }

编辑

getUserName代码:

class GetRequest{

  String messageAlert;

  Future<void> getUserName(String _token) async {
    var response = await http.get("${ApiService.url}/dashboard", 
        headers: <String, String>{
        "accept": "application/json",
        "authorization": "Bearer " + _token,
        //"token": _token,
    });
    var responseBody = json.decode(response.body);
    mData = ModelUserData.fromJson(responseBody);
  }
  
}

这是mData:

class ModelUserData{

  String fullname;

  ModelUserData({
    this.fullname
  });

  ModelUserData.fromJson(Map<String,dynamic> parseJson){
    fullname = parseJson['full_name'];
  }

}
  
var mData = ModelUserData();

2 个答案:

答案 0 :(得分:1)

首先,您的@override上有一个错字,没有initState标签。应该是这样的:

@override
void initState() {
    super.initState();

然后,您不会显示mData的来源。通常,必须提供业务逻辑代码。这样就是GetRequest()

无论如何,最简单的方法是使getUserName像这样:

Future<String> getUserName(String token) async {
     // do your thing
     return userName;
}

这样,您可以等待getUserName并在返回时进行重建。就像在initState中一样(像标记一样,创建一个userName State变量):

() async {
    userName = await GetRequest().getUserName(token);
    setState((){}); // this triggers the widget to rebuild
}();

现在,小部件将在请求解决后重新生成,您可以在UI代码中直接使用userName变量。

但是,随着您的应用程序的增长,这将很快变得乏味。要使其更清洁,请学习state management

答案 1 :(得分:1)

我将您的方法getUserName更改为返回数据,而不是在其中分配mData

class GetRequest{

    String messageAlert;

    Future<ModelUserData> getUserName(String _token) async {
        var response = await http.get("${ApiService.url}/dashboard", 
            headers: <String, String>{
            "accept": "application/json",
            "authorization": "Bearer " + _token,
            //"token": _token,
        });
        var responseBody = json.decode(response.body);
        return ModelUserData.fromJson(responseBody);
    }
}

然后在initState上做

@override
void initState() {
    GetRequest().getUserName(token).then((model) => {
        setState(() => mData = model);
    })

    super.initState();        
} 

这里重要的是在模型到达时校准setState