gpt4 book ai didi

整个应用程序的 Flutter 集中/通用加载屏幕

转载 作者:行者123 更新时间:2023-12-03 08:05:56 29 4
gpt4 key购买 nike

我正在 Riverpod Auth 流程样板应用程序中工作。

我想对所有异步功能甚至登录和注销使用通用加载屏幕。目前,如果 Appstate 加载我显示加载屏幕,我有 AppState 提供程序。它可以正常登录,但我不知道这是好方法还是坏方法。

我可以使用此加载屏幕来执行应用程序中的所有异步任务吗?

AuthWidget:

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

@override
Widget build(BuildContext context, WidgetRef ref) {
AppState appState = ref.watch(appStateProvider);

if(appState.isLoading){
return const Center(child: CircularProgressIndicator(color: Colors.red),);
}
return appState.isAuthenticated ? const HomePage() : const SignIn();
}
}

应用程序状态:

class AppState {
User? user;
bool isLoading;
bool isAuthenticated;

AppState(this.user, this.isLoading, this.isAuthenticated);

}

AuthRepository:

class AuthRepository extends StateNotifier<AppState>{

AuthRepository() : super(AppState(null,false,false));

Future<void> signIn()async {
state = AppState(null,true,false);

await Future.delayed(const Duration(seconds: 3));
User user = User(userName: 'FakeUser', email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f0a0c1a0d3f18121e1613511c1012" rel="noreferrer noopener nofollow">[email protected]</a>');
AppState appState = AppState(user, false, true);
state = appState;
}

}

final appStateProvider = StateNotifierProvider<AuthRepository,AppState>((ref){
return AuthRepository();
});

最佳答案

回答你的问题:是的,你可以。

我在这里唯一要更改的是您的 AppState 的内容:我将使用专用于触发您的 Loader 的 LoadingState 。

以下是我喜欢在应用程序中使用通用加载程序来管理屏幕的方式。

1 - 创建一个 LoadingState 并提供它

final loadingStateProvider = ChangeNotifierProvider((ref) => LoadingState());

class LoadingState extends ChangeNotifier {
bool isLoading = false;

void startLoader() {
if (!isLoading) {
isLoading = true;
notifyListeners();
}
}

void stopLoader() {
if (isLoading) {
isLoading = false;
notifyListeners();
}
}
}

2 - 使用“通用”加载器定义基页

class LoadingContainer extends ConsumerWidget {
const LoadingContainer({
Key? key,
required this.child,
}) : super(key: key);

final Widget child;

@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(loadingStateProvider);
return Stack(
children: [
child,
if (state.isLoading)
const Center(child: CircularProgressIndicator())
else
const SizedBox(),
],
);
}
}

3 - 每当我需要处理加载数据时就实现这个小部件。

return Scaffold(
backgroundColor: AppColor.blue,
body: LoadingContainer(
child: ...

然后我只需更新我的 loadingStateProvider 及其直接来自 Controller 或 Widget 的 isLoading

关于整个应用程序的 Flutter 集中/通用加载屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72323605/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com