skip to Main Content

So I am trying to get list of data that is provided by user as an input and display them by creating list of card but when I run the project I come up with an error LateInitializationError: Field ‘userModels’ has not been initialized. Not sure what is wrong with the code or I missed anything on the code.

    class UserPage extends StatefulWidget {
      @override
      _UserPageState createState() => _UserPageState();
    }
    
    class _UserPageState extends State<UserPage> {
      late List<UserModels>? userModels;
      bool isLoading = false;
    
      @override
      void initState() {
        super.initState();
    
        refreshUserPage();
      }
    
      @override
      void dispose() {
        RegDatabase.instance.close();
    
        super.dispose();
      }
    
      Future refreshUserPage() async {
        setState(() => isLoading = true);
    
       **//this.userModels = await RegDatabase.instance.readAllNotes();**
    
        setState(() => isLoading = false);
      }
    
      @override
      Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: Text(
            'Notes',
            style: TextStyle(fontSize: 24),
          ),
          actions: [Icon(Icons.search), SizedBox(width: 12)],
        ),
        body: Center(
          child: isLoading
              ? CircularProgressIndicator()
              : userModels!.isEmpty
              ? Text(
            'No Notes',
            style: TextStyle(color: Colors.white, fontSize: 24),
          )
              : buildNotes(userModels),
        ),
        floatingActionButton: FloatingActionButton(
          backgroundColor: Colors.black,
          child: Icon(Icons.add),
          onPressed: () async {
            await Navigator.of(context).push(
              MaterialPageRoute(builder: (context) => AddEditUserPage()),
            );
    
            refreshUserPage();
          },
        ),
      );

  Widget buildNotes(userModels) => Container(
      child: ListView.builder(
          itemCount: userModels.length,
          padding: const EdgeInsets.only(top: 10.0),
          itemBuilder: (context, index) {
            return BabyCard(userModels[index]);
          })
  );
}

3

Answers


  1. You’re making initState forced to be executed to completion with Futures left uncompleted. initState must be synchronous (cannot be async) and should not call any Future-producing routine (directly or indirectly) except to store that Future into a variable for later review.

    Login or Signup to reply.
  2. From your codes I understand that userModel can also be null but you are checking if its empty. you can also add if its null

    body: Center(
              child: isLoading
                  ? CircularProgressIndicator()
                  : userModels == null || userModels!.isEmpty
                  ? Text(
                'No Notes',
                style: TextStyle(color: Colors.white, fontSize: 24),
              )
                  : buildNotes(userModels),
            ),
    

    And don’t mark userModels as late since you are adding ? it means it can be null too.

     List<UserModels>? userModels;
    
    Login or Signup to reply.
  3. Just change this line :

    late List<UserModels>? userModels;
    

    To this one :

    List<UserModels> userModels = [];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search