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

1
  • i am struggling with this too, you got the solution? Commented Jul 25, 2020 at 6:19

4 Answers 4

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));
}
Sign up to request clarification or add additional context in comments.

2 Comments

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...
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 !
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.

Comments

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;
    });     
  }

Comments

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");    
      } 
  },)

2 Comments

why shall i use future builder? Isn't Bloc meant to handle different app states?
Actually , if you read FutureBuilder is used for handling asynchronous operations in the UI i.e connectionState, while the BLoC pattern is used for managing the application's state and business logic separately from the UI. So, If your requirements needs to mix this state you can do so.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.