Search code examples
flutterdartdio

How to get value from Future with custom model in flutter


I am calling an API to get data from server and i have created a dart file (model) from (https://javiercbk.github.io/json_to_dart/)

And now i want to access that future object value.

Main.dart

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Row(
          children: <Widget>[
            RaisedButton(
              child: Text("Click"),
              onPressed: () async{
                setState(() {
                  apiCall = true; // Set state like this
                });
                MemberLogin fMain = await getUser();
                print('$fMain ');
              },
            ),
          ],
        ),
      ),
    );
  }

  Future<MemberLogin> getUser() async {
    try {
      final String _endpoint =
          "https://api.com/";
      Dio dio = new Dio();
      Response response = await dio
          .post(_endpoint, data: {"new_data": "hello"});
      print("user API response - : $response ");
      setState(() {
        apiCall = false;
      });
      return MemberLogin.fromJson(response.data);
    } catch (error, stacktrace) {
      print("Exception occured: $error stackTrace: $stacktrace");
      //return MemberLogin.withError("$error");
    }
  }

MemberLogin.dart

class MemberLogin {
  int success;
  String message;

  MemberLogin({this.success, this.message});

  MemberLogin.fromJson(Map<String, dynamic> json) {
    success = json['success'];
    message = json['message'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['success'] = this.success;
    data['message'] = this.message;
    return data;
  }
}

Now when i print message from MemberLogin after my request MemberLogin fMain = await getUser(); . I had debug the code and i am able to see response but i can not print or access message string.

How can i do that ?


Solution

  • @deepak, i simulated an api and seems to be working fine. Have you tried accessing message as fMain.message? Please see the example below,

    class MyAppState extends State<MyApp> {
      bool apiCall = false;
      String message = '';
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(home: Scaffold(
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(message, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18.0),),
                RaisedButton(
                  child: Text("Click", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18.0),),
                  onPressed: () async{
                    apiCall = true; // Set state like this
                    MemberLogin fMain = await getUser();
                    message = fMain.message;
                    setState(() {
                    });
                    print('$fMain ');
                  },
                ),
              ],
            ),
          ),
        ));
      }
    
      Future<MemberLogin> getUser() async {
        try {
          final String _endpoint =
              "http://echo.jsontest.com/key/value/message/testmessage";
          Dio dio = new Dio();
          Response response = await dio
              .get(_endpoint);
          print("user API response - : $response ");
          setState(() {
            apiCall = false;
          });
          return MemberLogin.fromJson(response.data);
        } catch (error, stacktrace) {
          print("Exception occured: $error stackTrace: $stacktrace");
          //return MemberLogin.withError("$error");
        }
      }
    }
    
    class MemberLogin {
      String key;
      String message;
    
      MemberLogin({this.key, this.message});
    
      MemberLogin.fromJson(Map<String, dynamic> json) {
        key = json['key'];
        message = json['message'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['key'] = this.key;
        data['message'] = this.message;
        return data;
      }
    }
    
    

    demo