Home > Software design >  LateInitializationError when accessing a page for the first time in flutter mobile
LateInitializationError when accessing a page for the first time in flutter mobile

Time:05-10

Currently when I access a page in my flutter mobile app I get the following error

LateError (LateInitializationError: Field 'library' has not been initialized.)

When I save or refresh that page the data finally loads into the list and displays on page.

Here is the code I'm currently working with to display the title of the book in the library:

class DashboardScreen extends StatefulWidget {
  const DashboardScreen({Key? key}) : super(key: key);

  @override
  _DashboardScreen createState() => _DashboardScreen();
}

class _DashboardScreen extends State<DashboardScreen> {
  final storage = new FlutterSecureStorage();
  var baseUrl = dotenv.get('API_BASE_URL');
  late List<Library> library;
  var dataloaded = false;
  _getMangas() async {
    String? token = await storage.read(key: 'token');
    var url = Uri.parse(baseUrl   "/library/list");

    var response = await http.get(url, headers: {
      HttpHeaders.authorizationHeader: 'Bearer $token',
      HttpHeaders.acceptHeader: 'Application/Json'
    });
    library = libraryFromJson(response.body);
  }

  @override
  void initState() {
    super.initState();
    _getMangas();
    //_getMangas(token);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Sample'),
      ),
      body: ListView.builder(
        itemCount: library.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(library[index].title  
                ', Vol. '  
                library[index].volume.toString()),
          );
        },
      ),
      drawer: const MainDrawer(),
    );
  }
}

CodePudding user response:

It's because you are using library list inside ListView.builder and initially library list is not initialized. Add this line in initState() above _getMangas():
library = [];

CodePudding user response:

_getMangas() is an async function, hence library list is being initialized after being used inside the list view. You need to initialized library list with empty list before using it.

For your reference:

  @override
  void initState() {
    super.initState();
    library = [];
    _getMangas();
    //_getMangas(token);
  }
  • Related