Flutter自动登录记住我功能使用提供商



我正在尝试使用提供商为我的flutter web应用程序做自动登录功能。我找不到任何关于这个的文章或视频,我想知道它应该如何实现。我想做的是在启动网站之前检查共享偏好。App使用URL路由,所以我需要检查用户访问的URL。下面是我的主代码:

void main() {
setUrlStrategy(PathUrlStrategy());
setupLocator();
runApp(MultiProvider(
providers: [ChangeNotifierProvider(create: (_) => AppStateProvider())],
child: MyApp(),
));
}
class MyApp extends StatelessWidget {
final RouteInformationProvider? routeInformationProvider;
const MyApp({Key? key, this.routeInformationProvider}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'Title',
theme: ThemeData(
primarySwatch: Colors.grey,
fontFamily: 'Poppins'
),
// home: HomeView(),
routerDelegate: RoutemasterDelegate(
routesBuilder: (context) {
return buildRouteMap(context);
},
),
routeInformationParser: RoutemasterParser(),
routeInformationProvider: routeInformationProvider,
);
}
}

这是我的AppStateProvider类

class AppStateProvider extends ChangeNotifier {
bool loading = false;
AppStateModel? appState;
checkCaches() async {
loading = true;
final prefs = await SharedPreferences.getInstance();
final String? acToken = prefs.getString('accessToken');
if (acToken != null) {
appState?.isLoggedIn = true;
appState?.accessToken = acToken;
final String? comToken = prefs.getString('companyToken');
appState?.companyToken = comToken;
loading = false;
notifyListeners();
} else {
appState?.isLoggedIn = false;
notifyListeners();
}
}
storeCaches(String acToken, String? comToken) async {
loading = true;
final prefs = await SharedPreferences.getInstance();
prefs.setString('accessToken', acToken);
prefs.setString('companyToken', comToken!);
appState?.isLoggedIn = true;
appState?.accessToken = acToken;
appState?.companyToken = comToken;
loading = false;
notifyListeners();
}
}

对实现有什么想法吗?

我想消费者可能对你有用

这样的

Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: WebLocalStorage().userInfoNotif,
builder: (BuildContext context, User value, Widget child) {
return value == null
? HBLoginPageNew()
: HBHomePage(
user: WebLocalStorage.instance.user,
);
},
);}

这是我的自动输入代码。我用的是valuenofier。消费者使用ChangeNotifierProvider。

相关内容

  • 没有找到相关文章

最新更新