skip to Main Content

The Future builder in my Flutter app is fetching data twice, as opposed to fetching data just once.

class StudentListView extends StatefulWidget {
  @override
  State<StudentListView> createState() => _StudentListViewState();
}

class _StudentListViewState extends State<StudentListView> {

  List<StudentModel> students = [];

  late Future myFuture;

  Future<List<StudentModel>> getStudents() async {

    var response = await http.get(Uri.https(BASE_URL, APP_INTERSNSHIP_URL));

    var studentData = jsonDecode(response.body);

    for (var student in studentData) {

      final singlestudent = StudentModel(
          id: student["id"],
          name: student["name"]);
      students.add(singleStudent);
    }
    return students;
  }

  @override
  void initState() {
    myFuture = getstudents();
    super.initState();
  }

  Widget build(BuildContext context) {
    getstudents();
    return Scaffold(
      appBar: AppBar(
        title: Text(
          APP_TITLE,
        ),
        centerTitle: true,
      ),
      body: FutureBuilder(
          future: myFuture,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return ListView.builder(
                itemCount: students.length,
                itemBuilder: (context, index) {
                  return Container(
                    child: Card(
                      child: Padding(
                        padding: EdgeInsets.all(15.0),
                        child: Column(
                          children: [
                            Text(students[index].id.toString()),
                            Text(students[index].name.toString())
                          ],
                        ),
                      ),
                    ));
                });
            } else {
              return Center(child: CircularProgressIndicator());
            }
          })
    );
  }
}

I’ve followed various articles, but nothing is working. Still after doing this, the app is fetching data twice.

P.S.: Is this is a standard way to fetching data in Flutter or is there something better?

P.S.S: All required libraries are added in the code, and the code doesn’t have any errors. It is just fetching data twice.

2

Answers


  1. Chosen as BEST ANSWER
    Widget build(BuildContext context) {
        getstudents(); <------ culprit, called it twice
        return Scaffold(
            appBar: AppBar(
              title: Text(
                APP_TITLE,
              ),
              centerTitle: true,
            ),
            body: FutureBuilder(
                future: myFuture, <------ right place to call
    
    

  2. To answer your question, I guess you have already figured out, that you had called it twice,

    To add on to it, you could directly use getStudents in the future, instead of setting it to the variable myFuture

    body: FutureBuilder(
                future: getStudents(), // directly call it here 
    

    Remove the following lines

    late Future myFuture;
    
      @override
      void initState() {
        // myFuture = getstudents(); No more needed
        super.initState();
      }
    

    And you can aswell define List<StudentModel> students = []; inside the getStudents() as it is just used locally .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search