【发布时间】:2020-08-25 20:42:01
【问题描述】:
我看到 this 和 this 的问题有类似的问题,但没有一个答案适合我,也不知道为什么。
我需要检查在 y SharedPreferences 中是否有一个 bool 值应该设置 initialRoute 值。
这里是代码:
import 'package:consegne_cernusco/pages/consegna-gratuita.dart';
import 'package:consegne_cernusco/pages/onboarding.dart';
import 'package:consegne_cernusco/pages/single_shop.dart';
import 'package:flutter/material.dart';
import 'package:consegne_cernusco/pages/shop_list.dart';
import 'package:shared_preferences/shared_preferences.dart';
import './pages/home.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
// Future<bool> _shoudShowOnboardingPage;
Future<bool> _shoudShowOnboardingPage() async {
return _prefs.then((SharedPreferences p) {
// p.remove('shoudShowOnboardingPage');
return p.getBool('shoudShowOnboardingPage') ?? true;
});
}
String showMainPage() {
if (_shoudShowOnboardingPage().then((value) => value == true) == true) {
return OnBoarding.routeName;
}
return HomePage.routeName;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Consegne Cernusco',
theme: ThemeData(
primaryColor: Color(0xFF009EE4),
accentColor: Color(0xFF009FE3),
scaffoldBackgroundColor: Color(0xFFF3F5F7),
),
initialRoute: showMainPage(),
routes: {
HomePage.routeName: (ctx) => HomePage(),
ShopListPage.routeName: (ctx) => ShopListPage(),
SingleShopPage.routeName: (ctx) => SingleShopPage(),
ConsegnaGratuita.routeName: (ctx) => ConsegnaGratuita(),
OnBoarding.routeName: (ctx) => OnBoarding()
},
);
}
}
问题在于这一行:
if (_shoudShowOnboardingPage().then((value) => value == true) == true)
总是返回false,但无法理解如何管理它。
有什么建议吗?
【问题讨论】:
-
main() => SharedPreferences.getInstance().then((p) => p.getBool('shoudShowOnboardingPage')).then((b) => runApp(MyApp(b))) -
当然你必须添加带有
bool参数的MyApp构造函数 -
我已经尝试过您的解决方案,但没有成功:
flutterError (ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized. If you're running an application and need to access the binary messenger before runApp() has been called (for example, during plugin initialization), then you need to explicitly call the WidgetsFlutterBinding.ensureInitialized() first. -
您需要先显式调用
WidgetsFlutterBinding.ensureInitialized()。 -
所以:
main() { WidgetsFlutterBinding.ensureInitialized(); SharedPreferences.getInstance().then((p) => p.getBool('shoudShowOnboardingPage')).then((b) => runApp(MyApp(b))); }应该可以工作