我正在处理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();
}
}
- 您必须用
runApp(NewsApp());
结束main()
方法 - 将您的逻辑代码从
main()
方法移动到NewsApp
小部件 - 将
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,
);
}
}