how navigate screen in main page on flutter?

Issue

i want wait 5 seconds on main page and display loading animation then navigate to another page.
here is my code

import 'mainPage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'dart:async';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        backgroundColor: Colors.cyan,
        body: Builder(
          builder: (context) => Center(
            child: Container(
              child: SpinKitCubeGrid(color: Colors.white, size: 50.0),
            ),
          ),
        ),
      ),
    );
  }

  Future loadData() async {
    return new Timer(Duration(seconds: 5), () {
      setState(() {
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (context) => MainPage()));
      });
    });
  }
}

but i got this error:

Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.

what should i do?

Solution

Wrap MyApp with MaterialApp which will provide the right context to Navigator

void main() {
  runApp(MaterialApp(home: MyApp()));
}

Answered By – Jitesh Mohite

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *