title: How to get username and mail to display in UserAccountsDrawerHeader in flutter
body: <p>I am getting my response from the URL after login in but I can only print the data in my console but how to get the mail and name from the that response</p>
  <p>I have tried with the future response but when I get a future response but its returning error</p>
  <p>LoginPage.dart</p>
  <pre><code>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() =&gt; new _LoginPageState();
  }
  
  class _LoginPageState extends State&lt;LoginPage&gt; {
    final GlobalKey&lt;FormState&gt; _formKey = GlobalKey&lt;FormState&gt;();
    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: &lt;Widget&gt;[
                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: &lt;Widget&gt;[
                        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: &lt;Widget&gt;[
          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) =&gt; HomeScreen()),
      );
    }
  
    String _validateName(String value) {
      if (value.isEmpty) {
        return &quot;Username is Required&quot;;
      } else {
        username = value.toString();
      }
    }
  
    String _validatePassword(String value) {
      if (value.isEmpty) {
        return &quot;Password is Required&quot;;
      } else {
        password = value.toString();
      }
    }
  
    _submit() {
      if (_formKey.currentState.validate()) {
        _formKey.currentState.save();
        print(&quot;Username ${_loginData.username}&quot;);
        print(&quot;Password ${_loginData.password}&quot;);
        return SessionId();
      } else {
        setState(() {
          bool _validate = false;
        });
      }
    }
  
  
    final Dio _dio = Dio();
    PersistCookieJar persistentCookies;
    final String url = &quot;https://www.xxxx.in/rest/user/login.json&quot;;
  
    Future&lt;String&gt; get _localPath async {
      final directory = await getApplicationDocumentsDirectory();
      print(directory.path);
      return directory.path;
    }
  
    Future&lt;Directory&gt; get _localCoookieDirectory async {
      final path = await _localPath;
      final Directory dir = new Directory('$path/cookies');
      await dir.create();
      print(dir);
      return dir;
    }
  
    Future&lt;String&gt; 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: &quot;dio&quot;,
            &quot;Connection&quot;: &quot;keep-alive&quot;,
          },
        ); //BaseOptions will be persisted throughout subsequent requests made with _dio
        _dio.interceptors.add(
            InterceptorsWrapper(
                onResponse:(Response response) {
                  List&lt;Cookie&gt; cookies = persistentCookies.loadForRequest(Uri.parse(url));
                  csrfTokenValue = cookies.firstWhere((c) =&gt; c.name == 'csrftoken', orElse: () =&gt; 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(&quot;https://www.xxxx.in/rest/user/login.json&quot;);
        print(csrfTokenValue);
        return csrfTokenValue;
      } catch (error, stacktrace) {
        print(error);
  //      print(&quot;Exception occured: $error stackTrace: $stacktrace&quot;);
        return null;
      }
    }
  
     SessionId() async {
       try {
         final csrf = await getCsrftoken();
         FormData formData = new FormData.from({
           &quot;username&quot;: &quot;${_loginData.username}&quot;,
           &quot;password&quot;: &quot;${_loginData.password}&quot;,
           &quot;csrfmiddlewaretoken&quot; : '$csrf'
         });
         Options optionData = new Options(
           contentType: ContentType.parse(&quot;application/json&quot;),
         );
         Response response = await _dio.post(&quot;https://www.xxxx.in/rest/user/login.json&quot;, data: formData, options: optionData);
     Payload payloadFromJson(String str) =&gt; 
     Payload.fromJson(json.decode(str));
        String payloadToJson(Payload data) =&gt; json.encode(data.toJson());
         if (response.statusCode == 200){
           return Navigator.of(context).pushReplacement(MaterialPageRoute(
               builder: (context) =&gt; HomeScreen(),
           ));
         }
         else{
           throw Exception();
         }
       } on DioError catch(e) {
         if(e.response != null) {
           print( e.response.statusCode.toString() + &quot; &quot; + 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(&quot;Exception occured: $error stackTrace: $stacktrace&quot;);
         return null;
       }
     }
  }
  </code></pre>
  <p>Homepage.dart</p>
  <pre><code>import 'package:flutter/material.dart';
  ...
  
  class HomeScreen extends StatefulWidget {
    @override
    _HomeScreenState createState() =&gt; new _HomeScreenState();
  }
  class _HomeScreenState extends State&lt;HomeScreen&gt; {
    Widget build(BuildContext context) {
          return Scaffold(
            backgroundColor: Color(0xffF2F2F2),
            appBar: AppBar(
              title: Text('Home'),
              automaticallyImplyLeading: true,
             drawer: new Drawer(
             child: Column(
               children: &lt;Widget&gt;[
                 UserAccountsDrawerHeader(
                   accountName: Text(&quot;${globals.payload.user.name}&quot;),
                   accountEmail: Text(&quot;${globals.payload.user.mail}&quot;),
                   )
               ],
             )
           )
  }
  </code></pre>
  <p>please anybody can help to display name and mail-in drawer</p>
  <p>Here is my Json</p>
  <pre><code>{
      &quot;sessid&quot;: &quot;iszSjigXjxCvchpSRrU3j5Xp83t_LCXoIbwzx-mM3ag&quot;,
      &quot;session_name&quot;: &quot;SSESSb2a6bc76023596a5f4079539da5ffe57&quot;,
      &quot;token&quot;: &quot;zQESYCrGbL-3NzN8Lm-1ll3AQ-iCFYjiqRvxSpesGBc&quot;,
      &quot;user&quot;: {
          &quot;uid&quot;: &quot;991&quot;,
          &quot;name&quot;: &quot;abc&quot;,
          &quot;mail&quot;: &quot;abc@gmail.com&quot;,
          &quot;theme&quot;: &quot;&quot;,
          &quot;signature&quot;: &quot;&quot;,
          &quot;signature_format&quot;: &quot;plain_text&quot;,
          &quot;created&quot;: &quot;1560678471&quot;,
          &quot;access&quot;: &quot;1565326417&quot;,
          &quot;login&quot;: 1565328198,
          &quot;status&quot;: &quot;1&quot;,
          &quot;timezone&quot;: &quot;Asia/Kolkata&quot;,
          &quot;language&quot;: &quot;&quot;,
          &quot;picture&quot;: &quot;0&quot;,
          &quot;data&quot;: {
              &quot;mimemail_textonly&quot;: 0
          },
          &quot;uuid&quot;: &quot;9e614051-1f21-470a-9194-c567fced36f7&quot;,
          &quot;roles&quot;: {
              &quot;2&quot;: &quot;authenticated user&quot;,
              &quot;6&quot;: &quot;Mock test user&quot;
          },
          &quot;rdf_mapping&quot;: {
              &quot;rdftype&quot;: [
                  &quot;sioc:UserAccount&quot;
              ],
              &quot;name&quot;: {
                  &quot;predicates&quot;: [
                      &quot;foaf:name&quot;
                  ]
              },
              &quot;homepage&quot;: {
                  &quot;predicates&quot;: [
                      &quot;foaf:page&quot;
                  ],
                  &quot;type&quot;: &quot;rel&quot;
              }
          }
      }
  }
  </code></pre>
  <p>Find Json file <a href="https://i.stack.imgur.com/dhMje.png" rel="nofollow noreferrer">here</a></p>