user13111868
user13111868

Reputation:

Running the function only once while the program is running

I create an function with using rest api to get user data with using his ID.

my code in UI:

  SharedPreferences sharedPreferences;
  UserApiService userApiService;

  @override
  void initState() {
    super.initState();
    getUserData();
    userApiService = UserApiService();
  }

  Future<User> getUserData() async {
    sharedPreferences = await SharedPreferences.getInstance();
    int id = sharedPreferences.getInt('id');
    return userApiService.getUser(id);
  }

my code in api_service:

  Future<User> getUser(int id) async{
    final response = await client.get('$baseUrl/user/$id');
    if(response.statusCode == 200){
      return userFromJson(response.body);
    }else return null;
  }

here is my FutureBuilder:

  @override
  Widget build(BuildContext context){
    return FutureBuilder(
      future: getUserData(),
      builder: (context, snapshot){
        if(!snapshot.hasData){
          return Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.white,
              iconTheme: IconThemeData(color: Colors.black),
              title: Text('Profil', style: TextStyle(color: Colors.black, letterSpacing: 1),),
              elevation: 0.0,
              centerTitle: true,
              actions: <Widget>[
                IconButton(
                  icon: Icon(Icons.more_vert),
                  onPressed: () {
                    //
                  },
                )
              ],
              bottom: PreferredSize(child: Container(color: Colors.black, height: 0.1), preferredSize: Size.fromHeight(0.1),),
          ),
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
        User user = snapshot.data;
        return Scaffold(
          backgroundColor: Colors.white,
          body: Container(
            child: Text(user.firstName),
          ),
        );
      },
    );
  }

And I have a problem with the fact that every time I go to the page where my request is done, the function is reloaded and the information is retrieved from the server again.

How to make this data downloaded from my rest api only once and then displayed smoothly without having to make another request to the database for this data.

I know that I must use state management but i don't have any idea how to di this.

Thanks for any answer :)

Upvotes: 0

Views: 38

Answers (1)

chunhunghan
chunhunghan

Reputation: 54377

From https://github.com/flutter/flutter/issues/11426#issuecomment-414047398
Reason:

didUpdateWidget of the FutureBuilder state is being called every time a rebuild is issued. This function checks if the old future object is different from the new one, and if so, refires the FutureBuilder.

Solution:
So instead of having:

FutureBuilder(
  future: getUserData(),
....

We should have:

Future _future;

@override
initState() {
  super.initState();
  _future = getUserData();
}

and then

FutureBuilder(
  future: _future,

Upvotes: 1

Related Questions