Getting null error after fetching data from local db

Viewed 171

I am having a db with few profile information, I would like to load them in my dashboard after the login. here is my code in my dashboard screen.

class __DashboardPageState extends State<_DashboardPage> {

  UserClass userObject;
  var db;

  __DashboardPageState(){
    getUserObj();
  }
  void getUserObj() async{
    db = new DatabaseHelper();
    userObject = await db.fetchUsers();
  }


//-----------------

  @override
  Widget build(BuildContext context) {
    getUserObj();

    Container(
      padding: const EdgeInsets.only(bottom: 8),
      child: new Text(
        "Welcome Back, "+ userObject.firstname,
        style: TextStyle(
          fontFamily: "Yorkten_ConMed",
          fontSize: 14,
          color: Color(0xffffffff),
        ),
      ),
    )

The getter 'firstname' was called on null. Receiver: null Tried calling: firstname

Getting this as error in my console and screen is showing error like attached. I know due to async it is not initialized before the screen getting drawn. but i dont know how to pull and load the data in my widget from db apart from this. enter image description here

1 Answers

You need to handle the visibility of widget while the data is being loaded.

  • Instead of constructor use AfterLayout to load your data, once data is fetched from DB, do setState.
  • You can show loader while the data is being loaded by using package screen_loader.
  • You need to handle the possible null values

Like in your case it is obvious userObject will be null initially so when you are using userObject's properties use like this: userObject?.firstname ?? '-', here if either userObject or firstname is null then return '-'

Related