使用共享首选项的插件时出现问题



我正在处理flutter,共享首选项插件有问题这是我的代码:

import 'package:flutter/material.dart';
import 'package:newsapp/screens/homescreen.dart';
import 'package:newsapp/screens/onboarding.dart';
import 'package:shared_preferences/shared_preferences.dart';
void  main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
int seen1 = prefs.getInt('seen');
Widget _screen = HomeScreen();
if (seen1 == null || seen1 == 0)
_screen = OnBoarding();
else {
_screen = HomeScreen();
}
}
class NewsApp extends StatelessWidget {
final Widget _screen;
NewsApp(this._screen);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: this._screen,
);
}
}

这是错误消息:

没有提供首选的FlutterEngine。为此FlutterFragment创建一个新的FlutterEngine。D/FlutterActivityAndFragmentDelegate(1817(:将FlutterEngine附加到拥有此片段的活动。D/FlutterView(1817(:连接到FlutterEngine:io.flutter.embedding.engine.FlutterEngine@e2b1eab

我们需要在获得之前添加WidgetsFlutterBinding.ensureInitialized();

await SharedPreferences.getInstance();

类似:

void  main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
int seen1 = prefs.getInt('seen');
Widget _screen = HomeScreen();
if (seen1 == null || seen1 == 0)
_screen = OnBoarding();
else {
_screen = HomeScreen();
}
}
  1. 您必须用runApp(NewsApp());结束main()方法
  2. 将您的逻辑代码从main()方法移动到NewsApp小部件
  3. NewsApp小部件转换为StatefulWidget以适应SharedPreferences中的数据

像这样:

import 'package:flutter/material.dart';
import 'package:newsapp/screens/homescreen.dart';
import 'package:newsapp/screens/onboarding.dart';
import 'package:shared_preferences/shared_preferences.dart';
void  main() {
runApp(NewsApp());
}
class NewsApp extends StatefulWidget {
@override
_NewsAppState createState() => _NewsAppState();
}
class _NewsAppState extends State<NewsApp> {
final Widget _screen = HomeScreen();
@override
void initState() {
super.initState();
Future.delayed(Duration.zero, () async {
SharedPreferences prefs = await SharedPreferences.getInstance();
int seen1 = prefs.getInt('seen');
if (seen1 == null || seen1 == 0)
_screen = OnBoarding();
else {
_screen = HomeScreen();
}
setState(() {});
}
}
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: this._screen,
);
}
}

相关内容

  • 没有找到相关文章

最新更新