登录后我从URL得到响应,但是我只能在控制台中打印数据,但是如何从响应中获取邮件和名称
我尝试了将来的响应,但是当我得到将来的响应但返回错误
LoginPage.dart
import 'dart:io';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'globals.dart' as globals;
class LoginPage extends StatefulWidget {
static String tag = 'login-page';
@override
_LoginPageState createState() => new _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
LoginRequestData _loginData = LoginRequestData();
bool _validate = false;
bool _obscureText = true;
var username, password;
@override
Widget build(BuildContext context) {
return Scaffold(
// backgroundColor: Colors.white,
body: SingleChildScrollView(
child: Container(
color: Colors.lightGreen[500],
child: Column(
children: <Widget>[
Center(
child: Container(
width: MediaQuery
.of(context)
.size
.width,
height: MediaQuery
.of(context)
.size
.height / 2.5,
decoration: BoxDecoration(
gradient: LinearGradient(
// begin: Alignment.topCenter,
// end: Alignment.bottomCenter,
colors: [
Color(0xFFFFFFFF),
Color(0xFFFFFFFF),
]
),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(90)
)
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Align(
alignment: Alignment.center,
child: Image.asset('images/ic_launcher1.png'),
),
],
),
),
),
Center(
child: SingleChildScrollView(
child: new Form(
key: _formKey,
autovalidate: _validate,
child: _getFormUI(),
),
)
)
],
),
),
),
);
}
Widget _getFormUI() {
return new Column(
children: <Widget>[
SizedBox(height: 24.0),
Center(
child: Text('Login',
style: TextStyle(fontSize: 25,
fontWeight: FontWeight.bold,
color: Colors.white),),
),
new SizedBox(height: 25.0),
new TextFormField(
keyboardType: TextInputType.emailAddress,
autofocus: false,
decoration: InputDecoration(
hintText: 'Username',
contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)),
),
validator: _validateName,
onSaved: (value) {
_loginData.username = value;
},
),
new SizedBox(height: 8.0),
new TextFormField(
autofocus: false,
obscureText: _obscureText,
keyboardType: TextInputType.text,
decoration: InputDecoration(
hintText: 'Password',
contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(24.0)),
suffixIcon: GestureDetector(
child: Icon(
_obscureText ? Icons.visibility : Icons.visibility_off,
semanticLabel:
_obscureText ? 'show password' : 'hide password',
),
),
),
validator: _validatePassword,
onSaved: (String value) {
_loginData.password = value;
}
),
new SizedBox(height: 15.0),
new Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
onPressed: () {
_submit();
// Navigator.of(context).pushReplacementNamed('/home');
},
padding: EdgeInsets.all(12),
color: Colors.black54,
child: Text('Log In', style: TextStyle(color: Colors.white)),
),
),
new FlatButton(
child: Text(
'Forgot password?',
style: TextStyle(color: Colors.black54),
),
onPressed: () {},
),
new FlatButton(
onPressed: _sendToRegisterPage,
child: Text('Not a member? Sign up now',
style: TextStyle(color: Colors.black54)),
),
Text(''),
Text(''),
Text(''),
],
);
}
_sendToRegisterPage() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomeScreen()),
);
}
String _validateName(String value) {
if (value.isEmpty) {
return "Username is Required";
} else {
username = value.toString();
}
}
String _validatePassword(String value) {
if (value.isEmpty) {
return "Password is Required";
} else {
password = value.toString();
}
}
_submit() {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
print("Username ${_loginData.username}");
print("Password ${_loginData.password}");
return SessionId();
} else {
setState(() {
bool _validate = false;
});
}
}
final Dio _dio = Dio();
PersistCookieJar persistentCookies;
final String url = "https://www.xxxx.in/rest/user/login.json";
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
print(directory.path);
return directory.path;
}
Future<Directory> get _localCoookieDirectory async {
final path = await _localPath;
final Directory dir = new Directory('$path/cookies');
await dir.create();
print(dir);
return dir;
}
Future<String> getCsrftoken() async{
try {
String csrfTokenValue;
final Directory dir = await _localCoookieDirectory;
final cookiePath = dir.path;
persistentCookies = new PersistCookieJar(dir: '$cookiePath');
persistentCookies.deleteAll(); //clearing any existing cookies for a fresh start
_dio.interceptors.add(
CookieManager(persistentCookies) //this sets up _dio to persist cookies throughout subsequent requests
);
_dio.options = new BaseOptions(
baseUrl: url,
contentType: ContentType.json,
responseType: ResponseType.plain,
// connectTimeout: 5000,
// receiveTimeout: 100000,
headers: {
HttpHeaders.userAgentHeader: "dio",
"Connection": "keep-alive",
},
); //BaseOptions will be persisted throughout subsequent requests made with _dio
_dio.interceptors.add(
InterceptorsWrapper(
onResponse:(Response response) {
List<Cookie> cookies = persistentCookies.loadForRequest(Uri.parse(url));
csrfTokenValue = cookies.firstWhere((c) => c.name == 'csrftoken', orElse: () => null)?.value;
if (csrfTokenValue != null) {
_dio.options.headers['X-CSRF-TOKEN'] = csrfTokenValue; //setting the csrftoken from the response in the headers
}
print(response);
return response;
}
)
);
await _dio.get("https://www.xxxx.in/rest/user/login.json");
print(csrfTokenValue);
return csrfTokenValue;
} catch (error, stacktrace) {
print(error);
// print("Exception occured: $error stackTrace: $stacktrace");
return null;
}
}
SessionId() async {
try {
final csrf = await getCsrftoken();
FormData formData = new FormData.from({
"username": "${_loginData.username}",
"password": "${_loginData.password}",
"csrfmiddlewaretoken" : '$csrf'
});
Options optionData = new Options(
contentType: ContentType.parse("application/json"),
);
Response response = await _dio.post("https://www.xxxx.in/rest/user/login.json", data: formData, options: optionData);
Payload payloadFromJson(String str) =>
Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
if (response.statusCode == 200){
return Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (context) => HomeScreen(),
));
}
else{
throw Exception();
}
} on DioError catch(e) {
if(e.response != null) {
print( e.response.statusCode.toString() + " " + e.response.statusMessage);
print(e.response.data);
print(e.response.headers);
print(e.response.request);
} else{
print(e.request);
print(e.message);
}
}
catch (error, stacktrace) {
print("Exception occured: $error stackTrace: $stacktrace");
return null;
}
}
}
Homepage.dart
import 'package:flutter/material.dart';
...
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => new _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xffF2F2F2),
appBar: AppBar(
title: Text('Home'),
automaticallyImplyLeading: true,
drawer: new Drawer(
child: Column(
children: <Widget>[
UserAccountsDrawerHeader(
accountName: Text("${globals.payload.user.name}"),
accountEmail: Text("${globals.payload.user.mail}"),
)
],
)
)
}
请任何人都可以帮助显示姓名和邮寄抽屉
这是我的杰森
{
"sessid": "iszSjigXjxCvchpSRrU3j5Xp83t_LCXoIbwzx-mM3ag",
"session_name": "SSESSb2a6bc76023596a5f4079539da5ffe57",
"token": "zQESYCrGbL-3NzN8Lm-1ll3AQ-iCFYjiqRvxSpesGBc",
"user": {
"uid": "991",
"name": "abc",
"mail": "abc@gmail.com",
"theme": "",
"signature": "",
"signature_format": "plain_text",
"created": "1560678471",
"access": "1565326417",
"login": 1565328198,
"status": "1",
"timezone": "Asia/Kolkata",
"language": "",
"picture": "0",
"data": {
"mimemail_textonly": 0
},
"uuid": "9e614051-1f21-470a-9194-c567fced36f7",
"roles": {
"2": "authenticated user",
"6": "Mock test user"
},
"rdf_mapping": {
"rdftype": [
"sioc:UserAccount"
],
"name": {
"predicates": [
"foaf:name"
]
},
"homepage": {
"predicates": [
"foaf:page"
],
"type": "rel"
}
}
}
}
查找Json文件here
答案 0 :(得分:1)
在注释中,如何解析JSON?
请将您的JSON字符串粘贴到https://app.quicktype.io/
它将提供正确的格式
代码段以解析JSON。
// To parse this JSON data, do
//
// final payload = payloadFromJson(jsonString);
import 'dart:convert';
Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));
String payloadToJson(Payload data) => json.encode(data.toJson());
class Payload {
String sessid;
String sessionName;
String token;
User user;
Payload({
this.sessid,
this.sessionName,
this.token,
this.user,
});
factory Payload.fromJson(Map<String, dynamic> json) => new Payload(
sessid: json["sessid"],
sessionName: json["session_name"],
token: json["token"],
user: User.fromJson(json["user"]),
);
Map<String, dynamic> toJson() => {
"sessid": sessid,
"session_name": sessionName,
"token": token,
"user": user.toJson(),
};
}
class User {
String uid;
String name;
String mail;
String theme;
String signature;
String signatureFormat;
String created;
String access;
int login;
String status;
String timezone;
String language;
String picture;
Data data;
String uuid;
Map<String, String> roles;
RdfMapping rdfMapping;
User({
this.uid,
this.name,
this.mail,
this.theme,
this.signature,
this.signatureFormat,
this.created,
this.access,
this.login,
this.status,
this.timezone,
this.language,
this.picture,
this.data,
this.uuid,
this.roles,
this.rdfMapping,
});
factory User.fromJson(Map<String, dynamic> json) => new User(
uid: json["uid"],
name: json["name"],
mail: json["mail"],
theme: json["theme"],
signature: json["signature"],
signatureFormat: json["signature_format"],
created: json["created"],
access: json["access"],
login: json["login"],
status: json["status"],
timezone: json["timezone"],
language: json["language"],
picture: json["picture"],
data: Data.fromJson(json["data"]),
uuid: json["uuid"],
roles: new Map.from(json["roles"]).map((k, v) => new MapEntry<String, String>(k, v)),
rdfMapping: RdfMapping.fromJson(json["rdf_mapping"]),
);
Map<String, dynamic> toJson() => {
"uid": uid,
"name": name,
"mail": mail,
"theme": theme,
"signature": signature,
"signature_format": signatureFormat,
"created": created,
"access": access,
"login": login,
"status": status,
"timezone": timezone,
"language": language,
"picture": picture,
"data": data.toJson(),
"uuid": uuid,
"roles": new Map.from(roles).map((k, v) => new MapEntry<String, dynamic>(k, v)),
"rdf_mapping": rdfMapping.toJson(),
};
}
class Data {
int mimemailTextonly;
Data({
this.mimemailTextonly,
});
factory Data.fromJson(Map<String, dynamic> json) => new Data(
mimemailTextonly: json["mimemail_textonly"],
);
Map<String, dynamic> toJson() => {
"mimemail_textonly": mimemailTextonly,
};
}
class RdfMapping {
List<String> rdftype;
Name name;
Homepage homepage;
RdfMapping({
this.rdftype,
this.name,
this.homepage,
});
factory RdfMapping.fromJson(Map<String, dynamic> json) => new RdfMapping(
rdftype: new List<String>.from(json["rdftype"].map((x) => x)),
name: Name.fromJson(json["name"]),
homepage: Homepage.fromJson(json["homepage"]),
);
Map<String, dynamic> toJson() => {
"rdftype": new List<dynamic>.from(rdftype.map((x) => x)),
"name": name.toJson(),
"homepage": homepage.toJson(),
};
}
class Homepage {
List<String> predicates;
String type;
Homepage({
this.predicates,
this.type,
});
factory Homepage.fromJson(Map<String, dynamic> json) => new Homepage(
predicates: new List<String>.from(json["predicates"].map((x) => x)),
type: json["type"],
);
Map<String, dynamic> toJson() => {
"predicates": new List<dynamic>.from(predicates.map((x) => x)),
"type": type,
};
}
class Name {
List<String> predicates;
Name({
this.predicates,
});
factory Name.fromJson(Map<String, dynamic> json) => new Name(
predicates: new List<String>.from(json["predicates"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"predicates": new List<dynamic>.from(predicates.map((x) => x)),
};
}
在注释中,以下代码仅用于演示目的,而不是最佳实践,还有其他选择可以实现此目的,但是由于它是一个巨大的主题,因此很难一一列举,因此请参见Global Variables in Dart
1添加globals.dart文件
library my_prj.globals;
//import Payload class file too
Payload payload;
2在需要访问这些字段的任何地方导入该库。
import 'globals.dart' as globals;
...
globals.payload = payloadFromJson(jsonString); //from your parse or http logical
3在您的抽屉式课上
import 'globals.dart' as globals;
...
return Drawer(
child: Column(
children: <Widget>[
UserAccountsDrawerHeader(
accountName: Text("${globals.payload.user.name}"),
accountEmail: Text("${globals.payload.user.mail}"),
修改
在Homepage.dart中添加以下内容,然后即可访问全局变量
import 'globals.dart' as globals;
,然后在LoginPage.dart中执行相同的操作,则可以
globals.payload = payloadFromJson(jsonString);
答案 1 :(得分:1)
理论上,您将需要一个结构相似的对象。但是,如果JSON很复杂,并且您需要一个/两个属性,则可以采用以下快速方法。
_emailId = decodedBody["user"]["mail"]
现在,假设您在登录页面中获得JSON响应,并且需要将_emailId传递给HomePage。您可以按照以下步骤进行操作:
HomePage.dart
class HomePage extends StatelessWidget {
final String emailId;
const HomePage({
Key key,
@required this.emailId,
}) : super(key: key);
@override
Widget build(BuildContext context) {
print (this.emailid);
return .....
);
}
}
如下更新_sendToRegisterPage():
_sendToRegisterPage() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => HomeScreen(emailId:_emailId)),
);
}