2

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

4 Answers4

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));
}
Sukhi
  • 13,261
  • 7
  • 36
  • 53
  • Both works fine thanks. It seems taking some time to update the state. May be I'm on the emulator. However Any suggestions to load data faster at the startup... – Kasun Amarasinghe Mar 21 '20 at 06:49
  • 1
    Please accept the answer if it helps. It is difficult to tell 'methods' to load data faster without knowing the use case. Perhaps you can try loading smaller amount of data at the begining ? Or get the data in the previous screen and call this screen along with the data ! – Sukhi Mar 21 '20 at 12:12
0

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.
UTKARSH Sharma
  • 698
  • 1
  • 8
  • 17
0

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;
    });     
  }
shababhsiddique
  • 904
  • 3
  • 14
  • 40
0

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");    
      } 
  },)
Shivam Modi
  • 103
  • 1
  • 2
  • 10