NightyKnight
NightyKnight

Reputation: 33

Flutter Context Error in Navigator pushReplacement

I am creating a Splash Screen and I am getting Context error in Navigator push replacement

Following is the code for splash screen in main.dart file

import 'dart:async';
import 'package:number_trivia/pages/home.dart';

void main() {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    home: splash_screen(),
  ));
}

class splash_screen extends StatefulWidget {
  @override
  _splash_screenState createState() => _splash_screenState();
}

class _splash_screenState extends State<splash_screen> {
  @override
  void initState() {
    super.initState();
    Timer(Duration(seconds: 3),
          ()=>Navigator.pushReplacement(context,
              MaterialPageRoute(builder:
                (context) =>home()
              )
          )
     );
  }

  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: FlutterLogo(size: MediaQuery.of(context).size.height,),
    );
  }
}

The error says - The argument type 'JsObject' can't be assigned to the parameter type 'BuildContext'.

How do I correct it?

Any help will be much appreciated:)

Upvotes: 0

Views: 1632

Answers (2)

Fatemeh Hasheminasab
Fatemeh Hasheminasab

Reputation: 47

to that pushReplacement method, you passed a context which wasn't specified upper in the widget tree. try wrapping the screen with a widget that has a build method so that it creates a BuildContext that you can use. like this:

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
    debugShowCheckedModeBanner: false,
    home: splash_screen(context),
  );
  }
}

class splash_screen extends StatefulWidget {
  BuildContext context;
  splash_screen(this.context);


  @override
  _splash_screenState createState() => _splash_screenState();
}

class _splash_screenState extends State<splash_screen> {
  @override
  void initState() {
    super.initState();
    Timer(
        Duration(seconds: 3),
        () => Navigator.pushReplacement(
            widget.context, MaterialPageRoute(builder: (context) => home())));
  }

  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: FlutterLogo(
        size: MediaQuery.of(context).size.height,
      ),
    );
  }
}

does that help?

Upvotes: 1

MobIT
MobIT

Reputation: 980

When widget build completed, you can call Timer function.

 @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      Timer(Duration(seconds: 3), () {
        Navigator.pushReplacement(context,
              MaterialPageRoute(builder:
                (context) =>home()
              )
          );
      });
    });
  }

Upvotes: 1

Related Questions