gpt4 book ai didi

flutter - 如何让用户名和邮件显示在 UserAccountsDrawerHeader 中

转载 作者:IT王子 更新时间:2023-10-29 06:55:55 27 4
gpt4 key购买 nike

我在登录后从 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com