widget build method skips one statement on rebuild in flutter

Viewed 17

I have created a simple demo for jsondata with riverpod,

All going well but I can't understand one thing,

here is my Widget build method

Widget build(BuildContext context, WidgetRef ref) {
    final _data = ref.watch(userdataprovider);
    print("I am inside build");

and there is also a print statement inside that userdataprovider,

according to me this both print statement should be executed every rebuild but I am getting only once of userdataprovider's print, this is what I am failing to understand

here is my full code

final userprovider = Provider<Service>((ref) => Service());

final userdataprovider = FutureProvider<List<User>>((ref) {
  print("I am inside userdataprovider");
  return ref.watch(userprovider).getusers();
});

class CommentTab extends ConsumerWidget {
  const CommentTab({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final _data = ref.watch(userdataprovider);
    print("I am inside build");
    return Scaffold(
      backgroundColor: Color.fromRGBO(Random().nextInt(255),
          Random().nextInt(255), Random().nextInt(255), 1),
      body: _data.when(data: (_data) {
        List<User> userlist = _data.map((e) => e).toList();

        return Column(
          children: [
            Expanded(
                child: ListView.builder(
                    itemCount: userlist.length,
                    itemBuilder: (context, index) {
                      User user = userlist[index];

                      return mylisttile(user);
                    })),

          ],
        );
      }, error: (err, s) {
        return Text('Error Found');
      }, loading: () {
        return Center(child: CircularProgressIndicator());
      }),
    );
  }

1 Answers

I found this solution from a tutorial,

its a simple disposing..

final userdataprovider = FutureProvider.autoDispose<List<User>>((ref) {
  return ref.watch(userprovider).getusers();
});
Related