0
votes

I am stuck as being beginner. I want to post the rest api request in flutter using wordpress as backend. I can post the request in postman But don't know how to do this in flutter. As far as i write in flutter app.

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<JwtToken> createjwtToken(String username,String password) async {
  final http.Response response = await http.post(
    'http://e4sftttpqshahryar.atwebpages.com/wp-json/jwt-auth/v1/token',
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'username': username,
      'password': password,
    }),
  );

  if (response.statusCode == 201) {
    return JwtToken.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to create album.');
  }
}

class JwtToken {
  String token;
  String userEmail;
  String userNicename;
  String userDisplayName;

  JwtToken(
      {this.token, this.userEmail, this.userNicename, this.userDisplayName});

  JwtToken.fromJson(Map<String, dynamic> json) {
    token = json['token'];
    userEmail = json['user_email'];
    userNicename = json['user_nicename'];
    userDisplayName = json['user_display_name'];
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  final TextEditingController _controller = TextEditingController();
  final TextEditingController _controller1 = TextEditingController();
  Future<JwtToken> _futureJwt;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Create Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Create Data Example'),
        ),
        body: Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.all(8.0),
          child: (_futureJwt == null)
              ? Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    TextField(
                      controller: _controller,
                      decoration: InputDecoration(hintText: 'Enter Usernam'),
                    ),
                     TextField(
                      controller: _controller1,
                      decoration: InputDecoration(hintText: 'Enter Password'),
                    ),
                    RaisedButton(
                      child: Text('Create Data'),
                      onPressed: () {
                        setState(() {
                          _futureJwt = createjwtToken(_controller.text,_controller1.text);
                        });
                      },
                    ),
                  ],
                )
              : FutureBuilder<JwtToken>(
                  future: _futureJwt,
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      return Text(snapshot.data.token);
                    } else if (snapshot.hasError) {
                      return Text("${snapshot.error}");
                    }

                    return CircularProgressIndicator();
                  },
                ),
        ),
      ),
    );
  }
}

This can accomplish in Post man as.I only wanted the highlighted value in my app enter image description here.

I installed the Jwt plugin of the wordpress to make Jwt token. At the end my goal is to post the username and password in the **http://e4sftttpqshahryar.atwebpages.com/wp-json/jwt-auth/v1/token?username=shahryar&password=e4sftttpq So I can get Jwt token and make the function Login,Logout and update user and post information in the wordpress Site.**

1

1 Answers

2
votes

Finally after removing JsonEncode function in the http.post() //body . API is getting the jwt token as required.