简体   繁体   English

我正在 flutter 中实现 Splash Screen 我正在使用 sharedPreferences 我面临着延迟初始化错误

[英]I am implementing Splash Screen in flutter along with it i am using sharedPreferences I am facing late initialisation error in it

Here I have implemented splash screen and in main.dart I assigned it as home:SplashScreen();在这里,我实现了启动画面,在 main.dart 中,我将其指定为 home:SplashScreen(); Here I have also implemented sharedPreferences now I am facing late initialisation error for:static late SharedPreferences pref;在这里,我还实现了 sharedPreferences,现在我面临以下初始化错误:static late SharedPreferences pref; I can't understand how resolve it and where to declare pref variable import 'package:flutter/material.dart';我不明白如何解决它以及在哪里声明 pref 变量 import 'package:flutter/material.dart';

import 'package:onesignal_flutter/onesignal_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'View/LoginPage.dart';
import 'View/homePageAdmin.dart';

class SplashScreen extends StatefulWidget {
  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class SharedPrefService {
  static late SharedPreferences pref;

  static Future<void> init() async {
    await SharedPrefService.init();

    SharedPrefService.pref = await SharedPreferences.getInstance();
    var usrEmail = pref.getString('email');
    String usrname = pref.getString('username').toString();
  }
}

class _SplashScreenState extends State<SplashScreen> {
  String playerId = '';

  var usrEmail = SharedPrefService.pref.getString('email');
  String usrname = SharedPrefService.pref.getString('username').toString();
  @override
  void initState() async {
    SharedPrefService.pref = await SharedPreferences.getInstance();
    super.initState();
    await SharedPrefService.init();

    initPlatformState();

    _navigateToHome();
  }

  Future<void> initPlatformState() async {
    String usrname = SharedPrefService.pref.getString('username').toString();

    OneSignal.shared.setAppId('e89acaa4-5388-4e3a-bd69-44d197bdcbd7');
    // OneSignal.shared
    //     .promptUserForPushNotificationPermission()
    //     .then((accepted) {});
    final status = await OneSignal.shared.getDeviceState();
    final String? osUserID = status?.userId;
    print('The player id from main.dart ...........${osUserID}');
    // OneSignal.shared.setNotificationOpenedHandler(
    //     (OSNotificationOpenedResult result) async {
    //   var id1 = await result.notification.additionalData!["Docid"];

    //   final int docid = int.parse(id1).toInt();

    //   navigatorKey.currentState!.push(MaterialPageRoute(
    //       builder: (context) => DocumentsDetails(docid, usrname)));
    // });

    setState(() {
      this.playerId = osUserID!;
    });
    print('this.playerid from main.dart ${this.playerId}');
  }

  _navigateToHome() async {
    String pId = this.playerId;

    await Future.delayed(Duration(milliseconds: 1500), () {});
    Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => usrEmail == null
              ? LoginPage()
              : homePageAdmin(
                  pId,
                  usrname,
                ),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          child: Text(
            'Splash Screen',
            style: TextStyle(
                fontSize: 25,
                fontWeight: FontWeight.bold,
                color: Colors.blueAccent),
          ),
        ),
      ),
    );
  }
}

This error occurs when you use late variable before its initialization.当您在初始化之前使用late变量时会发生此错误。

Solution: making late variable to nullable variable, for example:解决方案:将late变量设为nullable变量,例如:

class SharedPrefService {
  static SharedPreferences? pref; // nullable variable

  static Future<void> init() async {
    await SharedPrefService.init();

    SharedPrefService.pref = await SharedPreferences.getInstance();
    var usrEmail = pref?.getString('email'); 
    String usrname = pref!.getString('username').toString();
  }
}

You cannot just make initState async and expect that to work.您不能只使initState async并期望它起作用。 Yes, it will be async, but since it is still returning void , it cannot be waited on.是的,它将是异步的,但由于它仍在返回void ,因此无法等待。 So, it will be called and then your program will continue without waiting for it.因此,它将被调用,然后您的程序将继续执行而无需等待它。

You seem to have a Future and not really an idea how to handle this inside a Flutter widget.你似乎有一个Future而不是真的知道如何在 Flutter 小部件中处理它。 I suggest getting a good overview:我建议得到一个很好的概述:

What is a Future and how do I use it? 什么是 Future 以及如何使用它?

The solution is to use some kind of state management to handle the fact that you are doing something in the background.解决方案是使用某种状态管理来处理您正在后台执行某些操作这一事实。 Your display cannot wait for it.您的显示器等不及了。 It has to be displayed.必须显示出来。 The obvious solution is some kind of spinner or loading screen while you are waiting for the Future to resolve.显而易见的解决方案是在您等待 Future 解决时使用某种微调器或加载屏幕。 There is a simple example of a FutureBuilder in the link above, or you can use more powerful solutions.上面的链接中有一个FutureBuilder的简单示例,或者您可以使用更强大的解决方案。 Personally, I prefer bloc , but there are many others, too.就个人而言,我更喜欢bloc ,但也有很多其他的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我在我的应用程序中使用颤振原生启动包作为启动屏幕 - I am using flutter native splash package for splash screen in my app 我无法解决颤动闪屏中的尺寸问题 - I am not able to solve the size problem in flutter splash screen 在 flutter 中尝试制作启动画面时出现错误 255,我该如何解决? - While trying to make splash screen with in flutter I am getting an error 255 how do I fix it? 我正在使用 Applovin 在我的 flutter 应用程序中实施广告,每当我运行该应用程序时都会收到此错误 - I am implementing ads in my flutter app using Applovin, anytime I run the app I get this error 我正在使用Flutter Preview 1 - Am I using Flutter Preview 1 我正在尝试使用 generateRoute 将多个 arguments 传递到 flutter 屏幕 - I am trying to pass multiple arguments to a flutter screen by using generateRoute 我在 flutter 中出现蓝色飞溅 animation 问题 - i am getting blue splash animation Problem in flutter 我试图在 flutter 中添加轮播 slider 但我面临缺少所需的参数错误 - i was trying to add a carousel slider in flutter but i am facing missing required param error 我在使用颤振平台方法频道的 kotlin 画中画问题上遇到了问题 - I am facing issue on kotlin picture in picture with flutter platform methodchannel 运行我的应用程序时,我在 Flutter 中遇到问题 - I am facing issue in Flutter while run my application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM