简体   繁体   中英

How to call api once in futurebuilder

My application have different routes and I would like to know how to call my api with cubit just once when the user come for the first time on the screen and also not to re-call the api every time he returns to the screen already initialized.

my structure use bloC

and this is my profile page initialization class

@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final user = context.read<AuthCubit>().state;
final bloc = context.read<ProfileCubit>();

return Scaffold(
  body: FutureBuilder(
    future: bloc.updateProfilePicture(user!.id),
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (snapshot.connectionState == ConnectionState.done) {
        return BlocBuilder<ProfileCubit, ProfilePicture?>(
          buildWhen: (prev, curr) => prev != curr,
          builder: (context, picture) {
            return picture != null
                ? Profil(profilePicture: picture, updateIndex: updateIndex)
                : Profil(updateIndex: updateIndex);
          },
        );
      }
      return Center(
        child: CircularProgressIndicator(
          color: Colors.orange,
        ),
      );
    },
  ),
);
}

There are many ways to solve this problem 1- easy (but not clean code) is to use boolean global varibal like isApiReqursted with default value (false) and when call the api set it to true 2- you can cache the response in the repoistory or bloc and make the api method frst check if there are data if there isit does not need to make http request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM