Consumer Widget + AsyncNotifierProviderFamily + FamilyAsyncNotifier Leading to Continous Unregulated Widget Rebuilds and State Updates

I am trying to create a simple FamilyAsyncNotifier for my Profile Consumer widget. However, for some reason, the state is continuously getting rebuilt and the build method in my FamilyAsyncNotifier keeps on getting executed.

What are best practices when working with this sort of thing?

// TheTimefrontendlibsrcfeaturesprofilepresentationprofile_screen.dart

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:frontend/src/features/profile/presentation/profile_screen_controller_wp.dart';


class ProfileScreen extends ConsumerWidget {
  const ProfileScreen({super.key, required this.userId, required this.isAdmin});

  final String userId;
  final bool isAdmin;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final controllerParams = ProfileScreenControllerParams(userId, isAdmin);
    final profileState = ref.watch(profileScreenControllerProvider(controllerParams));
    
    return Scaffold(
      appBar: AppBar(
        leading: OverflowBox(
          maxWidth: 80,
          child: Row(
            children: [
              IconButton(
                icon: const Icon(Icons.settings),
                onPressed: () {
                  // Handle settings icon pressed
                },
              ),
              IconButton(
                icon: const Icon(Icons.share),
                onPressed: () {
                  // Handle share icon pressed
                },
              ),
            ],
          ),
        ),
        title: profileState.when(
          data: (profile) { 
            return Center(
              child: Text('${profile?.firstName ?? ''} ${profile?.lastName ?? ''}'),
            );
          },
          loading: () {
            return const Center(child: CircularProgressIndicator());
          },
          error: (error, stackTrace) {
            return const Center(child: Text('Error'));
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.message),
            onPressed: () {
              // Handle messages icon pressed
            },
          ),
        ],
      ),
      body: profileState.when(
        data: (profile) {
          if (profile != null) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(height: 16),
                Row(
                  children: [
                    const SizedBox(width: 16),
                    const CircleAvatar(
                      radius: 40,
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          TextButton(
                            onPressed: () {
                              // Handle friends pressed
                            },
                            child: const Text('Friends'),
                          ),
                          TextButton(
                            onPressed: () {
                              // Handle followers pressed
                            },
                            child: const Text('Followers'),
                          ),
                          TextButton(
                            onPressed: () {
                              // Handle following pressed
                            },
                            child: const Text('Following'),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Text(
                    'Username: ${profile.username}',
                    style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                  ),
                ),
                const SizedBox(height: 8),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Text(
                    profile.biography ?? '',
                    style: const TextStyle(fontSize: 16),
                  ),
                ),
                const SizedBox(height: 16),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Row(
                    children: [
                      Expanded(
                        child: ElevatedButton(
                          onPressed: () {
                            // Handle create program pressed
                          },
                          child: const Text('Create Program'),
                        ),
                      ),
                      const SizedBox(width: 16),
                      Expanded(
                        child: ElevatedButton(
                          onPressed: () {
                            // Handle edit profile pressed
                          },
                          child: const Text('Edit Profile'),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            );
          } else {
            return const Center(child: Text('User not found'));
          }
        },
        loading: () {
          return const Center(child: CircularProgressIndicator());
        },
        error: (error, stackTrace) {
          return const Center(child: Text('Error occurred'));
        },
      ),
    );
  }
}
// TheTime\frontend\lib\src\features\profile\presentation\profile_screen_controller_wp.dart
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:frontend/src/features/profile/data/profile_repository_wp.dart';
import 'package:frontend/src/features/profile/domain/profile_model.dart';
import 'package:frontend/src/features/authentication/data/auth_repository_providers.dart';

//TODO: Figure out how to dispose of this appropriately.
//TODO: Figure out how to handle multiple controller/controller-provider instances simulataneouly. Probably another collections provider. 
//TODO: Above todos are kept for later.
//TODO: Need to add retry mechanisms and routes different flows depending on exception.

final profileScreenControllerProvider = AsyncNotifierProviderFamily<ProfileScreenController, Profile?, ProfileScreenControllerParams>(() {
  return ProfileScreenController();
});

class ProfileScreenControllerParams {
  final String userId;
  final bool isAdmin;
  ProfileScreenControllerParams(this.userId, this.isAdmin);
}

class ProfileScreenController extends FamilyAsyncNotifier<Profile?, ProfileScreenControllerParams> { //Remeber that ProfileScreenControllerParams is arg.

  @override //TODO: Consider storing references to obej
  FutureOr<Profile?> build(ProfileScreenControllerParams arg) async { //TODO this is getting stuck in some kind of infinite loop. Is there something wrong with my family implementation? //This is very bootleg!    
    return await getProfileById(arg.userId);    
  }

  Future<Profile?> getProfileById(String userId) async {
    state = const AsyncValue.loading();
    final profileRepository = ref.read(profileRepositoryProvider);
    try {
      final profile = profileRepository.getProfileById(userId);
      if (profile != null) {
        state = AsyncValue.data(profile);
        return profile;
      } else {
        await profileRepository.fetchRemoteProfileById(userId);
        final fetchedProfile = profileRepository.getProfileById(userId);
        if (fetchedProfile != null) {
          state = AsyncValue.data(fetchedProfile);
          return fetchedProfile;
        } else {
          state = AsyncValue.error(Exception('Profile not found'), StackTrace.current);
          return null;
        }
      }
    } catch (e, stackTrace) {
      state = AsyncValue.error(e, stackTrace);
      return null;
    }
  }
}

I have tried to return parameters directly like

final profileScreenControllerProvider = AsyncNotifierProviderFamily<ProfileScreenController, Profile?, ProfileScreenControllerParams>(
  (ref, params) {
    return ProfileScreenController(ref, params);
  },
  dependencies: [profileRepositoryProvider],
).autoDispose();```

But AsyncNotifierProviderFamily does not want you to pass parameters when creating instances of the FamilyAsyncNotifier.

I want to avoid using generator as I want to manually implement my providers.

New contributor

Neil Gawande is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật