How to connect a flutter mobile app to a rest API in node js which is hosted in heroku?

Viewed 1249

I have deployed a rest API (nodejs) in Heroku but i want to know how to connect my flutter mobile app with these endpoints.I have looked for solution but i haven't seen anything regarding this.my flutter app is running in my mobile device.Hope any one can give a good solution.

1 Answers
import 'package:http/http.dart' as http;

First import http package do mention that in pubspec,yaml then Import convert package if you want to deal with jsondata

import 'dart:convert';

Now you will be creating future functions for get request:

Future<void> getGoodRequest1() async{
    var url = 'your url';
    http.Response response = await http.get(url);
    String data = response.body;
    
    print(jsonDecode(data));
    

  }

for post request

Future<void> postGoodRequest2() async{

String url = 'your url';
Map<String, String> headers = {"Content-type": "application/json"};
// if you want to pass json along with it
    String json = '{"query": "example", "data": "example"}';
    // make POST request
    http.Response response = await http.post(url, headers: headers, body: json);
    // check the status code for the result
    print('posted');

  }

For more you can refer here Http flutter

Related