Getting null error after fetching data from local db

2

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

flutter
dart
sqflite
asked on Stack Overflow May 16, 2020 by Bala • edited May 16, 2020 by Uwe Keim

1 Answer

0

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 '-'

answered on Stack Overflow May 16, 2020 by Arnold Parge • edited May 16, 2020 by Arnold Parge

User contributions licensed under CC BY-SA 3.0