Home > Blockchain >  How to integrate Node JS API with Flutter APP?
How to integrate Node JS API with Flutter APP?

Time:01-07

I have created simple API to store Username and Password in Node JS. Now i want to connect with Flutter. And I am using http package in flutter.HTTP version So anyone can help me with this ?

I have tried this..

void _saveForm() {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
    }

    var data = {
      "email": formData['email'].toString(),
      "password": formData['password'].toString(),
    };
    // ignore: avoid_print
    print(data);

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => Home(),
      ),
    );
  }

CodePudding user response:

You can simply do this by following few simple steps.

  1. Creating the API in nodejs (which you already have)
  2. Connect your computer to a wifi network and type command ipconfig on the terminal. Copy the ipv4 address and then you can make a request to your node server from the mobile app (flutter) in the following way:
  3. If your using the physical emulator (your mobile phone) make sure it is connected to the same network as your pc is.

Post Request:

http.Response response = await http.post(
          Uri.parse('http://192.168.68.58:4000/YOUR-API'),
          headers: {
            'Content-Type': 'application/json; charset=UTF-8',
          },
          body: jsonEncode(
              <String, String>{'username': "Amarendra", 'password': "baahubali"}),
        );

Access the reponse body:

  variableName = jsonDecode(response.body);

Get Request:

  http.Response response = await http.get(
      Uri.parse('IPAddress/YOUR-API'),
      headers: {
        'Content-Type': 'application/json; charset=UTF-8',
      },
    );
    print(response.body);

You can wrap the above code in a function, and place the function in the stateful widget.

Later you can call this function from the void initState()

I always make this implementation in my apps. Hope it works for you as well.

  • Related