我被初学者所困扰。我想使用wordpress作为后端在flutter中发布其余api请求。我可以在邮递员中发布请求,但不知道如何处理。据我在Flutter应用程序中编写的内容。
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();
},
),
),
),
);
}
}
我安装了wordpress的Jwt插件来制作Jwt令牌。最后,我的目标是将用户名和密码发布在** http://e4sftttpqshahryar.atwebpages.com/wp-json/jwt-auth/v1/token?username=shahryar&password=e4sftttpq中,这样我就可以获得Jwt令牌并使功能Login,Logout并更新用户并在wordpress网站中发布信息。**
最后删除JsonEncode
中的http.post() //body
功能。 API正在根据需要获取jwt令牌。