Home > Software engineering >  flutter error LateInitializationError: Field '_instance@21075166' has not been initialized
flutter error LateInitializationError: Field '_instance@21075166' has not been initialized

Time:01-25

This is the middle part of the main that is expected to cause the error. If you are not logged in on the splash screen, this code goes to MyHomePage and logs in. If you are logged in, it goes to MainScreen and switches to the main screen of the app.

  class SplashScreen extends StatefulWidget {
      @override
      _SplashScreenState createState() => _SplashScreenState();
    }
    
    class _SplashScreenState extends State<SplashScreen> {
    
      final FirebaseAuth auth = FirebaseAuth.instance;
      final User? user = FirebaseAuth.instance.currentUser;
    
      @override
      void initState() {
        super.initState();
        _initUser().whenComplete((){
          setState(() {});
        });
      }
    
      _initUser() async {
        if (auth.currentUser != null) {
          Timer(
            Duration(seconds: 2),
                () => Navigator.of(context).pushAndRemoveUntil(
                    MaterialPageRoute(
                        builder: (context) =>
                            MainScreen(user!)),
                        (Route<dynamic> route) => false),
          );
        } else {
          Timer(Duration(seconds: 1),
                  () => Navigator.of(context).pushAndRemoveUntil(
                      MaterialPageRoute(
                          builder: (context) =>
                              MyHomePage()),
                          (Route<dynamic> route) => false),
          );
        }
      }
    
      @override
      Widget build(BuildContext context) {
    
        return Scaffold(
            body: Center(
              child: Text("Splash Screen"),
            ),
    
        );
      }
    }

This is the MyHomePage widget that is passed when you are not logged in.

class MyHomePage extends StatefulWidget {
      const MyHomePage({Key? key}) : super(key: key);
    
      @override
      State<MyHomePage> createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: TextButton(
              onPressed: (){
    
                FirebaseService().signup(context);
              },
              child: Text('Google'),
            ),
          )
        );
      }
    }
    class FirebaseService{
    
      final FirebaseAuth auth = FirebaseAuth.instance;
      final GoogleSignIn googleSignIn = GoogleSignIn();
    
      Future<void> signup(BuildContext context) async {
    
    
      final GoogleSignInAccount? googleSignInAccount = await googleSignIn.signIn();
      if (googleSignInAccount != null) {
        final GoogleSignInAuthentication googleSignInAuthentication =
        await googleSignInAccount.authentication;
        final AuthCredential authCredential = GoogleAuthProvider.credential(
            idToken: googleSignInAuthentication.idToken,
            accessToken: googleSignInAuthentication.accessToken);
    
        // Getting users credential
        UserCredential result = await auth.signInWithCredential(authCredential);
        User? user = result.user;
    
    
        if (user != null) {
          Navigator.push(
              context, MaterialPageRoute(builder: (context) => MainScreen(user)));
        }  // if result not null we simply call the MaterialpageRoute,
        // for go to the HomePage screen
      }
    }
    
      Future<void> signOutFromGoogle() async{
        await googleSignIn.signOut();
        await auth.signOut();
      }
    }

This is the content of the error

  The following LateError was thrown building MainScreen(dirty, dependencies: [_InheritedProviderScope<Pro?>], state: _MainScreenState#efcfa):
LateInitializationError: Field '_instance@21075166' has not been initialized.

The relevant error-causing widget was: 
  MainScreen MainScreen:file:///F:/flutter project/good_man/lib/main.dart:75:25
When the exception was thrown, this was the stack: 
#0      ScreenUtil._instance (package:flutter_screenutil/screen_util.dart)
#1      new ScreenUtil (package:flutter_screenutil/screen_util.dart:26:12)
#2      SizeExtension.sp (package:flutter_screenutil/size_extension.dart:14:20)
#3      _MainScreenState.build (package:good_man/mainscreen.dart:45:36)
#4      StatefulElement.build (package:flutter/src/widgets/framework.dart:4904:27)
#5      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4788:15)
#6      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4962:11)
#7      Element.rebuild (package:flutter/src/widgets/framework.dart:4511:5)
#8      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2713:19)
#9      WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:882:21)
#10     RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:363:5)
#11     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15)
#12     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1081:9)
#13     SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:862:7)
(elided 4 frames from class _RawReceivePortImpl, class _Timer, and dart:async-patch)

Below is the MainScreen code

class MainScreen extends StatefulWidget {
  const MainScreen(this.user);

  final User user;

  @override

  _MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
  @override
  Widget build(BuildContext context) {

    final User user = widget.user;
    final pro = Provider.of<Pro>(context);
    return DefaultTabController(
      length: 3,
      child: Scaffold(

          appBar: PreferredSize(
              preferredSize: Size.fromHeight(60.0), // here the desired height
              child: AppBar(
                iconTheme: IconThemeData(color: Colors.black),
                backgroundColor: pro.backColor_main,
                elevation: 0.0,
                centerTitle: true,
                title: Text('aaa',
                  style: TextStyle(
                      fontFamily: 'Gugi',
                      fontSize: 20.sp,
                      color: Colors.black,
                  ),),
              ),
          ),
          drawer: Drawer(
            child: ListView(
              padding: EdgeInsets.zero,
              children: [
                DrawerHeader(
                  child: Text('Drawer Header'),
                  decoration: BoxDecoration(
                    color: Colors.white
                  ),
                ),
                ListTile(
                  title: Text('aaa'),
                  onTap: () {
                    Navigator.pop(context);
                  },
                ),

              ],
            ),
          ),
          bottomNavigationBar: BottomBar(),
          body: Stack(children:  [

            TabBarView(
              children:  [
                MainTest(),
                Text(''),
                Main_User(user),
              ],
            ),
          ])),
    );
  }
}

This is the provider class

class Pro with ChangeNotifier{
  late List<int> GumBool;
  late List<String> Gname;

  Color backColor_white1 = Color(0xffEFEFEF);
  Color backColor_main = Color(0xffB5B7C3);
  Color backColor_main2 = Color(0xffD3D4DD);


  readyGumBool(){
    GumBool =[];
    GumBool = GumBool.toList();
  }
  setGumBool(int num){
    GumBool.add(num);
  }
  changeGumBool(int i, int num){
    GumBool[i] = num;
  }
  getGumBool(int num)=>GumBool[num];





  readyGname(){
    Gname=[];
    Gname = Gname.toList();
  }
  setGname(String ttt) {
    Gname.add(ttt);
  }
  getGname(int num)=>Gname[num];


}

Sorry for posting all the code without tidying up. -flutter clean -flutter upgrade -flutter create . Clear cache or emulator wipe I tried it, but it didn't work

CodePudding user response:

Please follow this documentation and add ScreenUtilInit as a root widget, specifying the size of the design draft before use, the width and height of the design draft. Example:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //Set the fit size (Find your UI design, look at the dimensions of the device screen and fill it in,unit in dp)
    return ScreenUtilInit(
      designSize: Size(360, 690),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: () =>
          MaterialApp(
            //... other code
            builder: (context, widget) {
              //add this line
              ScreenUtil.setContext(context);
              return MediaQuery(
                //Setting font does not change with system font size
                data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
                child: widget,
              );
            },
            theme: ThemeData(
              textTheme: TextTheme(
                //To support the following, you need to use the first initialization method
                  button: TextStyle(fontSize: 45.sp)
              ),
            ),
          ),
    );
  }
}

CodePudding user response:

Please, remove the delay added inside the _initUser() as this is the issue for this error.

  •  Tags:  
  • Related