Flutter:How to get data from Api before loading page

Viewed 8245

I was Trying To Get Data From Api To show on screen ,So i create one function and call it from widget build function or i also try to call it from constructor but it will call that function in the end so list empty error comes .

I Want to call api before screen load and store data in the List.

1 Answers

You can do it by the below code:

First you have to Hit Api with a onPressed or onTap method within a Button like

onPressed: () {
  getNutritionDetails(context,"2");
  getDataFromMyApi(context);
},

Then make a function to make the code more clean and reader with any name, here i named the function as getDataFromMyApi

void getDataFromMyApi(BuildContext context) {
    //Getting data from API and store it in String or Model or List whatever you required.
    String myData;

    //and then pass the data to your second activity
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) =>
            MyStatefulWidget(myData), // Your Api response myData is Passing to Stateful Widget
      ),
    );
  }

and then i made a Stateful Widget where you want to pass the data and wants it to load data before it is opened and there you can have your data before the page loads in myData var.

class MyStatefulWidget extends StatefulWidget {
  String myData;

  MyStatefulWidget(this.myData, {Key key}) : super(key: key);

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

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: double.infinity,
        width: double.infinity,
      child: Text(widget.myData),
    );
  }
}

OR

You Can Use Future Builder

Ques: What does Future Builder do?

Ans: It calls the future function to wait for the result, and as soon as it produces the result it calls the builder function where we build the widget.

class _ExampleState extends State<Example> {

@override
Widget build(BuildContext context) {
  return FutureBuilder<String>(
    future: downloadData(), // function where you call your api
    builder: (BuildContext context, AsyncSnapshot<String> snapshot) {  // AsyncSnapshot<Your object type>
      if( snapshot.connectionState == ConnectionState.waiting){
          return  Center(child: Text('Please wait its loading...'));
      }else{
          if (snapshot.hasError)
            return Center(child: Text('Error: ${snapshot.error}'));
          else
            return Center(child: new Text('${snapshot.data}'));  // snapshot.data  :- get your object which is pass from your downloadData() function
      }
    },
  );
}
Future<String> downloadData()async{
  //   var response =  await http.get('https://getProjectList');    
  return Future.value("Data download successfully"); // return your response
}
}
Related