Navigate to a new screen in Flutter

后端 未结 7 1432
日久生厌
日久生厌 2020-12-11 18:34

How do you navigate to a new screen in Flutter?

These questions are similar, but are asking more than I am.

  • Flutter - Navigate to a new screen, and cle
7条回答
  •  一个人的身影
    2020-12-11 19:18

    Navigate to a new screen:

    Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewScreen()));
    

    where context is the BuildContext of a widget and NewScreen is the name of the second widget layout.

    Code

    main.dart

    import 'package:flutter/material.dart';
    
    void main() => runApp(MyApp());
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(primarySwatch: Colors.blue),
          home: HomeScreen(),
        );
      }
    }
    
    class HomeScreen extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('Home Screen')),
          body: Center(
            child: RaisedButton(
              child: Text(
                'Navigate to a new screen >>',
                style: TextStyle(fontSize: 24.0),
              ),
              onPressed: () {
                _navigateToNextScreen(context);
              },
            ),
          ),
        );
      }
    
      void _navigateToNextScreen(BuildContext context) {
        Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewScreen()));
      }
    }
    
    class NewScreen extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('New Screen')),
          body: Center(
            child: Text(
              'This is a new screen',
              style: TextStyle(fontSize: 24.0),
            ),
          ),
        );
      }
    }
    

    See also

    • Documentation
    • Navigator and Routes and Transitions... Oh, My! - Simon Lightfoot | Flutter Europe

提交回复
热议问题