当前位置: 首页 > 知识库问答 >
问题:

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

酆英达
2023-03-14

我在登录后从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}"),
                 )
             ],
           )
         )
}

请任何人可以帮助显示姓名和邮箱抽屉

这是我的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 文件

共有2个答案

荀辰钊
2023-03-14

理论上,您需要一个具有类似结构的对象。但是,如果JSON很复杂,您需要一个/两个属性,那么下面的方法可以很快实现。

_emailId = decodedBody["user"]["mail"]

现在,假设您在登录页面中获得JSON响应,并且需要将_emailId传递给主页。您可以像下面这样操作:

主页

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)),
    );
  }
越涵衍
2023-03-14

在注释中,如何解析JSON?< br >

请将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)),
    };
}

在注释中,下面的代码仅用于演示目的,不是最佳实践,还有其他选项可以做到这一点,但很难说,因为这是一个巨大的主题,所以从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}"), 

在主页中编辑
。dart添加以下属性,然后可以访问全局变量

import 'globals.dart' as globals;

并在LoginPage.dart中执行同样的操作,然后您就可以

 globals.payload = payloadFromJson(jsonString);
 类似资料:
  • 我已经做了很多方法来只显示Firebase数据库的用户名。但是我得到了空值。也许你可以帮助我解决这个问题。 这是我拥有的数据库。我的Firebase数据库。 然后这是显示用户名的活动显示用户名的活动 这是我创建的动画,以便您可以更轻松地理解它。动画动图 这是我的密码 第一个活动.Java LoginActivity.Java 注册活动.Java 用户.Java

  • 我试图将我当前用户的用户名添加到我的URL(route)中,但是我不断地得到错误。我已经尝试了很多下面提到的方法,但是没有一个有效。以下是我的代码: Layout.html: 当我尝试转到另一个页面时,我收到错误,当我转到设置时收到404。 jinja2.exceptions.UndefinedError jinja2.exceptions.UndefinedError:'user'未定义 MOD

  • 我想在使用Firebase进行身份验证的Flutter应用程序中获取登录用户的电子邮件。 我可以通过以下方式获取当前用户 但是如果我用这个去取信 我得到以下错误: 在这种情况下,如何获取登录用户的电子邮件?

  • 我从我的域帐户发送消息,但他们不显示在用户(从nodemailer的选项)发送box.But当从gmail服务发送消息时,消息显示在已发送的user.Am我在下面的代码中缺少一些东西?

  • 在我的问题中,我使用NetBeans创建了单独的jframes。一个是使用textfield输入用户名和密码字段的登录框架。一旦登录,你就会进入下一个框架,回家。现在,我在home框架上放置了一个标签,以显示登录用户的名称。现在我想知道如何获得应用在登录框中的用户名来显示在这个标签中。提前感谢…在这方面的任何帮助都是非常感谢的。谢了。我想从登录框架中获取登录用户名以显示在主框架中。我尝试了以下代码

  • 我正在尝试允许用户搜索一个数据库和回显结果,事情是我想搜索多个表。我知道我可以从x1,x2中选择*,但是行的名称是其他的,所以当另一行是username2时,我不能回显$row['username']。也许,如果它是可能的,类似于if($row==whatever),idk。谢谢你的帮助。 编辑:找到了这样做的方法。类似这样的工作: