flutter getx 中对 null 值使用的 Null 检查运算符

yog*_*der 4 get nullpointerexception nul flutter flutter-getx

Null check operator used on a null value尽管我在代码中找不到任何空值,但我的代码给出了错误。

我不知道哪个屏幕实际上导致了错误,但肯定是这两个屏幕中的一个

  1. 启动画面
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tajicEasy/ui/auth/landingPage.dart';
import 'mySharedPreferences.dart';
import 'onBoarding_page.dart';

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

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    super.initState();
    loadSplashScreen();
    myAppState();
  }

  bool isFirstTimeOpen = false;

  myAppState() {
    MySharedPreferences.instance
        .getBooleanValue("firstTimeOpen")
        .then((value) => setState(() {
              isFirstTimeOpen = value;
            }));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: Image.asset(
          "assets/images/logo.png",
          width: double.infinity,
        ),
      ),
    );
  }

  Future<Timer> loadSplashScreen() async {
    return Timer(Duration(seconds: 3), onDoneLoadind);
  }

  onDoneLoadind() async {
    Get.offAll(() => isFirstTimeOpen ? LandingPage() : OnBoardingPage());
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. 载入画面
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:tajicEasy/controller/authController.dart';
import 'package:tajicEasy/controller/userController.dart';
import 'package:tajicEasy/ui/auth/login_in.dart';
import 'package:tajicEasy/ui/widgets/bottomNavigationBar.dart';

class LandingPage extends GetWidget<AuthController> {
  @override
  Widget build(BuildContext context){
    return GetX(initState:  maininit(),
        builder: (_) {
      print("here1");
      if (Get.find<AuthController>().user!=null) {
        print("here1");
        return Login();
      } else {
        print("here1");
        return AppMain();
      }
    });
  }

  maininit() {
    print("here");
   Get.put<UserController>(UserController());
    print("here");
    Get.put<AuthController>(AuthController());
    print("here");
  }
}
Run Code Online (Sandbox Code Playgroud)

我尝试loadSplashScreen();在 setState 之后放置myAppState() ,但之后出现相同的错误

检查isFirstTimeOpen不为空

Pau*_*chi 8

使用 getx 包时,您需要在 main.dart 中添加 GetMaterialApp()

在 main.dart 中替换此代码

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
     ...
     return MaterialApp(
     ...
     );
  }
Run Code Online (Sandbox Code Playgroud)

有了这个

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
      ...
      return GetMaterialApp(
      ...
      );
  }
Run Code Online (Sandbox Code Playgroud)