- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我在登录后从 URL 收到了我的回复,但我只能在我的控制台中打印数据,但如何从该回复中获取邮件和姓名
我已经尝试过 future 的响应,但是当我得到一个 future 的响应但返回错误时
登录页面.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;
}
}
}
主页.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}"),
)
],
)
)
}
请任何人帮忙显示姓名和邮寄抽屉
这是我的 Json
{
"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
最佳答案
在评论中,如何解析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);
关于flutter - 如何让用户名和邮件显示在 UserAccountsDrawerHeader 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57413117/
我想在文本区域中向许多其他用户发送电子邮件。在名为内容的文本区域中,如果我键入星号包围的“用户”,我想让它们填写每个电子邮件的用户名(“@”之前的文本)。每封电子邮件中的每个用户名都会产生很多不同。然
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: Problem when loading php file into variable (Load resu
我正在从数据库中提取信息,并尝试将其作为电子邮件发送。将从数据库中拉取多行数据。这就是我的代码的样子... 所有的信息邮件都很好。我的问题是,我想保留中断。例如,在标题之后,我想中断一下,然后开始备
当我使用我们使用 java 邮件的门户发送 TEXT 电子邮件时没有问题,但是,当我选择放置 HTML 内容并发送电子邮件时,会引发以下警报。花了几个小时搜索但没有有用的答案! 谁能帮忙 电子邮件主题
我有这个类,它处理 gmail 的登录。无论我输入什么电子邮件和密码,程序都会返回 session 。我不明白如何在返回 session 对象之前检查登录是否成功。 package mailActio
我设置的短信作为文本文件附在信中。我不明白为什么会这样。 replied letter example public void sendEmail(MimeMessage message, Strin
所以我正在制作一个网络系统,这个想法是当用户关闭浏览器时它会向我发送一封电子邮件。目前,用户正在使用 Javascript Ajax 来让 PHP 更新数据库的当前时间。当时间超过 5 分钟时,我希望
我想发送邮件,当产品从之前、日期和之后过期时,在 php 中,我在 php 中使用了 datediff mysql 函数,但如果产品过期日期类似于 31-1-2012 ,则不同值是不适合我的编码,请帮
我正在尝试设置一个邮件脚本,该脚本将首先从 mysql 运行一个简单的选择,并在消息中使用这些数组变量。然而,所有的变量并没有输出到消息体,只有一行变量。这是我的脚本: $sql1 = "SE
我最近一直在努力研究这个问题。是否有我可以使用并添加到其中的 android API?我想为电子邮件应用程序制作一个插件,但我不想制作整个电子邮件应用程序。 我非常想要一些已经可以处理发送和接收电子邮
嗨 我有一个 PHP 西类牙文网站。在此邮件正文中包含一个主题“Solicitud de cotización”,但该主题出现在热门邮箱中,如 Solicitud de cotización 。但它在
我想写一个脚本,使用 php 自动向我的客户发送电子邮件 我如何自动发送它,例如,如果他们输入他们的电子邮件。然后点击提交 我想自动发送这封邮件 其次,我的主机上是否需要 smtp 服务器?我可以在任
今天早上我已经解决了一个问题: Java Mail, sending multiple attachments not working 这次我遇到了一个稍微复杂一点的问题:我想将附件和图片结合起来。
下面是用于连接 IMAP 文件夹并对其执行操作的代码。所以我的问题是关于 javax.mail.Session 的,在这种情况下它会每秒重新创建一次(取决于 checkInbox() 的 hibern
我正尝试按照 http://www.tutorialspoint.com/java/java_sending_email.htm 上的指南发送电子邮件 Java 应用程序 当我尝试运行它时,从上面的链
我有一个包含 2 列 email 和 id 的表格。我需要找到密切相关的电子邮件。例如: john.smith12@example.com 和 john.smith12@some.subdomains
首先是一些信息: Debian 压缩 PHP 5.3.3 带有 mod_cgi 的 PHP 在这种情况下,我绝对必须使用 mail()。对于我所有的其他项目,我已经使用 SMTP 邮件。 我已将站点超
在对电子邮件主机的联系表单进行故障排除时,他们告诉我在 php 邮件功能的发件人地址中使用“-f”。 “-f”标志的作用是什么?为什么它可以解决允许发送电子邮件的问题?我阅读了一些文档,但不是很清楚。
一个简单的问题:群发邮件哪个性能好? mail() 函数或sendmail 流行的 PHP 列表管理器包使用哪个? 最佳答案 嗯,mail() 函数并不适合批量发送电子邮件,因为它会为您发送的每封
我正在制作一个 PHP 表单,允许用户上传附件并将其发送到我的电子邮件。我一直在寻找很长一段时间才能做到。最后,我找到了这个。 http://www.shotdev.com/php/php-mail/
我是一名优秀的程序员,十分优秀!