'How to load initial state data from sqlite database when Flutter app open

I'm making a simple Notepad app using flutter. I want to load already saved data from the SQLite database and initialize the state when the app opens. I tried with the initState() method with the async method. But async methods are not working in the initState() method. Some places say to use Future builder and BLoCs. But I'm not quite sure which is good. What is the best way to implement this in flutter??



Solution 1:[1]

You've two options.

Option 1 : Do what @UtakarshSharma says. Sample implementation below.

@override
  void initState() {
    super.initState();
    _requestSqlData();     
  }

void _requestSqlData(){
   _requestSqlDataAsync();  
}

void _requestSqlData() async {
    var _data = await getData();    // call API/await function to get the data
}

Option 2 : Use a call back method after the full-screen load. And use setState to update the screen. You'll have to use flutter_after_layout (https://github.com/slightfoot/flutter_after_layout) It executes the function after layout is completed. :

void initState() {
    super.initState();
    WidgetsBinding.instance
        .addPostFrameCallback((_) => myAwesomeFunction(context));
}

Solution 2:[2]

If you know how to load data from sql lite then define that function outside of initstate() using async and await and call it in initstate() . Initstate can't be async because it must need to run before your main app so we can use an outside function for same.

  1. Define function named sqlData() Using async await
  2. Call it inside initstate.

Solution 3:[3]

I found this approach to work for me. use .then() on your async function

@override
  void initState() {
    super.initState();
    db.getData().then((value){
      _valueState = value;
    });     
  }

Solution 4:[4]

Futures are the best way to handle data fetching and displaying them in your custom widget.

    late Future<YourDataType> dataItems;
    @override
    void initState(){
      super.initState();
      dataItems = getData();
    }

You can also add try-catch inside this method

    Future<YourDataType> getData() async{
      return await yourEndPointToFetchData();
    }

Inside the builder use FutureBuilder like this

    FutureBuilder<YourDataType>(
    future: dataItems,
    builder: (context, snapshot) {
      switch (snapshot.connectionState){
        case ConnectionState.none:
          return const Center(child: Text("your message"));
        case ConnectionState.active:
        case ConnectionState.waiting:
          return  const Center(child: CircularProgressIndicator());   
        case ConnectionState.done:
          if(snapshot.data == null || snapshot.data.items.isEmpty){
            return const Center(child: Text("no data"),);
          }
          return yourWidget(snapshot.data.items);
        default:
          return const Text("Your message");    
      } 
  },)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sukhi
Solution 2 UTKARSH Sharma
Solution 3 shababhsiddique
Solution 4 Shivam Modi