1

I am new to flutter and needs help in a small segment of code. Although my code works but it shows an error/red screen first(for milliseconds). When I get email of logged in user in this way: this._user?.email, it shows:

A non-null String must be provided to a Text widget. Failed assertion: 'data != null'

And when I get email in this way: _user.email, it shows:

The getter 'email' was called on null.

Receiver: null

Tried calling: email

Kindly suggest how to throw and catch this exception or fix this issue. Any kind of help would be highly appreciated and opinion is welcome. My full piece of code is here:

class MyAccountSetting extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: AccountSetting(),
    );
  }
}

class AccountSetting extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new AccountSettings();
  }
}

class AccountSettings extends State<AccountSetting> {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  FirebaseUser _user;

  @override
  void initState() {
    super.initState();
    initUser();
  }
  initUser() async {
    _user = await _auth.currentUser();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                margin: const EdgeInsets.only(top: 10.0),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  IconButton(
                    icon: Icon(Icons.mail),
                    iconSize: 30,
                    onPressed: () {},
                  ),
                  Text(
                    _user.email,
//                    this._user?.email,
                    style: TextStyle(fontSize: 18),
                  ),
                ],
              ),
            ]
        ),
      ),
    );
  }
}

1 Answer 1

2

What do you want to show while you're waiting for the user to be retrieved? For example if you want to show an empty string ('') you can write something like:

_user == null ? '' : _user.email

or even shorter:

_user?.email ?? ''

This way if the _user is null you will show an empty string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.