Flutter 问题:如何导航到另一个页面

Posted

技术标签:

【中文标题】Flutter 问题:如何导航到另一个页面【英文标题】:Flutter Problem: How to navigate to another page 【发布时间】:2021-09-11 12:17:20 【问题描述】:

我有一个问题,当我登录时我的页面没有进入主页,但是我不知道为什么。 并且数据可能没有进入提交功能,那么也许这就是登录没有完成的原因,我不明白登录将如何发生。

这是我的 auth.dart


import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:login_and_signup/Utils/api.dart';
import 'package:login_and_signup/Utils/http_exception.dart';

class Auth with ChangeNotifier 
  var MainUrl = Api.authUrl;

  Future<void> Authentication(String user_name, String user_email,
      String mobile_no, String password, String action) async 
    try 
      // var url = Uri.parse('$MainUrl/accounts:$endpoint?key=$AuthKey');
      var url = Uri.parse('$MainUrl&action=$action');
      print(url);
      if (action == 'registration') 
        final responce = await http.post(url, headers: 
          "Accept": "Application/json"
        , body: 
          "user_name": user_name,
          'user_email': user_email,
          "mobile_no": mobile_no,
          "password": password,
        );

        print("Response" + responce.body);
        final responceData = json.decode(responce.body);
        print("responceData" + responceData);

       else 
        final responce = await http.post(url, headers: 
          "Accept": "Application/json"
        , body: 
          "user_name": user_name,
          'user_email': user_email,
          "username": mobile_no,
          "password": password,
        );

        print("Response" + responce.body);
        final responceData = json.decode(responce.body);
        print("responceData" + responceData);
       
      


     catch (e) 
      throw e;
    
  

  Future<void> login(
      String user_name, String user_email, String mobile_no, String password) 
    return Authentication(user_name, user_email, mobile_no, password, 'login');
  

  Future<void> signUp(
      String user_name, String user_email, String mobile_no, String password) 
    return Authentication(
        user_name, user_email, mobile_no, password, 'registration');
  


这是我的 login.dart


import 'package:flutter/material.dart';
import 'package:login_and_signup/Providers/auth.dart';
import 'package:login_and_signup/Screens/home_screen.dart';
// import 'package:login_and_signup/Providers/login_auth.dart';
import 'package:login_and_signup/Screens/signup.dart';
import 'package:login_and_signup/Utils/http_exception.dart';
import 'package:provider/provider.dart';

class LoginScreen extends StatefulWidget 
  // static const String routeName = "/login";

  @override
  _LoginScreenState createState() => _LoginScreenState();


class _LoginScreenState extends State<LoginScreen> 
  final GlobalKey<FormState> _formKey = GlobalKey();

  TextEditingController _mobileController = new TextEditingController();
  TextEditingController _passwordController = new TextEditingController();

  Map<String, String> _authData = 
    'user_name': '',
    'user_email': '',
    'username': '',
    'password': ''
  ;

  Future _submit() async 
    print('aa' + _authData['user_name']!);
    if (!_formKey.currentState!.validate()) 
      //invalid

      return;
    
    _formKey.currentState!.save();
    try 
      await Provider.of<Auth>(context, listen: false).login(
          _authData['user_name']!,
          _authData['user_email']!,
          _authData['username']!,
          _authData['password']!)  .then((_) 
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (context) => HomePage()));
      );;
      print('aaaa');

     catch (e) 
     
    
  

  @override
  Widget build(BuildContext context) 
    // TODO: implement build
    return Scaffold(
      // backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Container(
          child: Stack(
            children: <Widget>[
              Container(
                height: MediaQuery.of(context).size.height * 0.65,
                width: MediaQuery.of(context).size.width * 0.85,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                        topRight: Radius.circular(360),
                        bottomRight: Radius.circular(360)),
                    color: Colors.blue),
              ),
              Container(
                padding:
                    EdgeInsets.only(top: 50, left: 20, right: 20, bottom: 50),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      "Sign In",
                      style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 40),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      "Sign in with your username or email",
                      style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 10),
                    ),
                    Form(
                      key: _formKey,
                      child: Container(
                        padding: EdgeInsets.only(top: 50, left: 20, right: 20),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              "username",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 12),
                            ),
                            TextFormField(
                              // obscureText: true,
                              controller: _mobileController,
                              style: TextStyle(color: Colors.white),
                              decoration: InputDecoration(
                                  enabledBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  prefixIcon: Icon(
                                    Icons.***_key,
                                    color: Colors.white,
                                  )),
                              validator: (value) 
                                if (value!.isEmpty || value.length < 1) 
                                  return 'valid no';
                                
                              ,
                              onSaved: (value) 
                                _authData['username'] = value!;
                              ,
                            ),
                            SizedBox(
                              height: 10,
                            ),
                           
                            SizedBox(
                              height: 10,
                            ),
                            Text(
                              "Password",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 12),
                            ),
                            TextFormField(
                              controller: _passwordController,
                              obscureText: true,
                              style: TextStyle(color: Colors.white),
                              decoration: InputDecoration(
                                  enabledBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  prefixIcon: Icon(
                                    Icons.***_key,
                                    color: Colors.white,
                                  )),
                              validator: (value) 
                                if (value!.isEmpty || value.length < 5) 
                                  return 'Password is to Short';
                                
                              ,
                              onSaved: (value) 
                                _authData['password'] = value!;
                              ,
                            ),
                            Container(
                              padding: EdgeInsets.only(top: 40),
                              width: 140,
                              child: RaisedButton(
                                  onPressed: () 
                                    print(_authData['username']);
                                    print(_authData['password']);
                                    _submit();
                                  ,
                                  shape: RoundedRectangleBorder(
                                    borderRadius:
                                        new BorderRadius.circular(10.0),
                                  ),
                                  child: Text(
                                    'Sign In',
                                    style: TextStyle(color: Colors.white),
                                  ),
                                  color: Colors.green),
                            ),
                            Align(
                              alignment: Alignment.bottomRight,
                              child: InkWell(
                                onTap: () 
                                  Navigator.of(context).push(MaterialPageRoute(
                                      builder: (ctx) => SignUpScreen()));
                                ,
                                child: Container(
                                  padding: EdgeInsets.only(top: 90),
                                  child: Text(
                                    "Create Account",
                                    style: TextStyle(
                                        decoration: TextDecoration.underline,
                                        color: Colors.blue,
                                        fontSize: 16),
                                  ),
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  

  void _showerrorDialog(String message) 
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: Text(
          'An Error Occurs',
          style: TextStyle(color: Colors.blue),
        ),
        content: Text(message),
        actions: <Widget>[
          FlatButton(
            child: Text('Okay'),
            onPressed: () 
              Navigator.of(context).pop();
            ,
          )
        ],
      ),
    );
  


这是我的注册.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:login_and_signup/Providers/auth.dart';
import 'package:login_and_signup/Providers/signup_auth.dart';
// import 'package:login_and_signup/Providers/signup_auth.dart';
import 'package:login_and_signup/Screens/home_screen.dart';
import 'package:login_and_signup/Screens/login.dart';
import 'package:login_and_signup/Utils/http_exception.dart';

import 'package:provider/provider.dart';

class SignUpScreen extends StatefulWidget 
  @override
  _SignUpScreenState createState() => _SignUpScreenState();


class _SignUpScreenState extends State<SignUpScreen> 
  final GlobalKey<FormState> _formKey = GlobalKey();

  Map<String, String> _authData = 
    'user_name': '',
    'user_email': '',
    'mobile_no': '',
    'password': '',
  ;
  TextEditingController _nameController = new TextEditingController();
  TextEditingController _emailController = new TextEditingController();
  TextEditingController _mobileController = new TextEditingController();
  TextEditingController _passwordController = new TextEditingController();

  Future _submit() async 
    if (!_formKey.currentState!.validate()) 
      //invalid
      return;
    
    _formKey.currentState!.save();
    try 
      await Provider.of<Auth>(context, listen: false).signUp(
          _authData['user_name']!,
          _authData['user_email']!,
          _authData['mobile_no']!,
          _authData['password']!)  .then((_) 
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (context) => HomePage()));
      );;     catch (e) 

    
  

  @override
  Widget build(BuildContext context) 
    // TODO: implement build
    return Scaffold(
      // backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Container(
          child: Stack(
            children: <Widget>[
              Container(
                height: MediaQuery.of(context).size.height * 0.65,
                width: MediaQuery.of(context).size.width * 0.85,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                        topRight: Radius.circular(360),
                        bottomRight: Radius.circular(360)),
                    color: Colors.blue),
              ),
              Container(
                padding:
                    EdgeInsets.only(top: 50, left: 20, right: 20, bottom: 50),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      "Sign Up",
                      style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 40),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      "Sign up with username or email",
                      style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 10),
                    ),
                    Form(
                      key: _formKey,
                      child: Container(
                        padding: EdgeInsets.only(top: 50, left: 20, right: 20),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              "name",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 12),
                            ),
                            TextFormField(
                              // obscureText: true,
                              controller: _nameController,
                              style: TextStyle(color: Colors.white),
                              decoration: InputDecoration(
                                  enabledBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  prefixIcon: Icon(
                                    Icons.person,
                                    color: Colors.white,
                                  )),
                              validator: (value) 
                                if (value!.isEmpty) 
                                  return 'Please Enter name';
                                
                              ,
                              onSaved: (value) 
                                _authData['user_name'] = value!;
                              ,
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            Text(
                              " Email",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 12),
                            ),
                            TextFormField(
                              controller: _emailController,
                              style: TextStyle(color: Colors.white),
                              decoration: InputDecoration(
                                  enabledBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  prefixIcon: Icon(
                                    Icons.person,
                                    color: Colors.white,
                                  )),
                              validator: (value) 
                                if (value!.isEmpty || !value.contains('@')) 
                                  return 'Invalid email';
                                
                              ,
                              onSaved: (value) 
                                _authData['user_email'] = value!;
                              ,
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            Text(
                              "mobile",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 12),
                            ),
                            TextFormField(
                              // obscureText: true,
                              controller: _mobileController,
                              style: TextStyle(color: Colors.white),
                              decoration: InputDecoration(
                                  enabledBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  prefixIcon: Icon(
                                    Icons.***_key,
                                    color: Colors.white,
                                  )),
                              validator: (value) 
                                if (value!.isEmpty || value.length < 10) 
                                  return 'valid no';
                                
                              ,
                              onSaved: (value) 
                                _authData['mobile_no'] = value!;
                              ,
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            Text(
                              "Password",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 12),
                            ),
                            TextFormField(
                              obscureText: true,
                              controller: _passwordController,
                              style: TextStyle(color: Colors.white),
                              decoration: InputDecoration(
                                  enabledBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  prefixIcon: Icon(
                                    Icons.***_key,
                                    color: Colors.white,
                                  )),
                              validator: (value) 
                                if (value!.isEmpty || value.length < 5) 
                                  return 'Password is to Short';
                                
                              ,
                              onSaved: (value) 
                                _authData['password'] = value!;
                              ,
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            Text(
                              "Confirm Password",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 12),
                            ),
                            TextFormField(
                              obscureText: true,
                              style: TextStyle(color: Colors.white),
                              decoration: InputDecoration(
                                  enabledBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(color: Colors.white),
                                  ),
                                  prefixIcon: Icon(
                                    Icons.***_key,
                                    color: Colors.white,
                                  )),
                              validator: (value) 
                                if (value != _passwordController.text) 
                                  return 'Password doesnot match';
                                
                              ,
                            ),
                            Container(
                              padding: EdgeInsets.only(top: 40),
                              width: 140,
                              child: RaisedButton(
                                  onPressed: () 
                                    print(_authData['mobile_no']);
                                    print(_authData['password']);
                                    _submit();
                                  ,
                                  shape: RoundedRectangleBorder(
                                    borderRadius:
                                        new BorderRadius.circular(10.0),
                                  ),
                                  child: Text(
                                    'Sign Up',
                                    style: TextStyle(color: Colors.white),
                                  ),
                                  color: Colors.green),
                            ),
                            Align(
                              alignment: Alignment.bottomRight,
                              child: InkWell(
                                onTap: () 
                                  Navigator.of(context).push(MaterialPageRoute(
                                      builder: (ctx) => LoginScreen()));
                                ,
                                child: Container(
                                  padding: EdgeInsets.only(top: 90),
                                  child: Text(
                                    "Sign In",
                                    style: TextStyle(
                                        decoration: TextDecoration.underline,
                                        color: Colors.blue,
                                        fontSize: 16),
                                  ),
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  

  void _showerrorDialog(String message) 
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: Text(
          'An Error Occurs',
          style: TextStyle(color: Colors.blue),
        ),
        content: Text(message),
        actions: <Widget>[
          FlatButton(
            child: Text('Okay'),
            onPressed: () 
              Navigator.of(context).pop();
            ,
          )
        ],
      ),
    );
  


【问题讨论】:

我已经测试了伪造身份验证的登录页面,它似乎有效。您是否有任何异常或未打印的内容? 不,我没有得到任何异常。 好吧,你不能得到任何异常,因为你有空块捕获是错误的代码。如果您不打算处理异常,它应该只通过应用程序。也许你没有注意到他们 【参考方案1】:

点击登录时遇到什么错误?您可以尝试使用路由生成器类

class RouteGenerator 
  static Route<dynamic>? generateRoute(RouteSettings settings) 
    // Getting arguments passed in while calling Navigator.pushNamed
    final args = settings.arguments;

    switch (settings.name) 
      case '/'://this will the first page get loaded
        return MaterialPageRoute(builder: (_) => LoginPage());
      case '/home':
        return MaterialPageRoute(builder: (_) => MyHomePage());
   
  



From  the main.dart call the initial page as follows
 
class MyApp extends StatelessWidget 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      initialRoute: '/',//
      onGenerateRoute: RouteGenerator.generateRoute,


    );

  

将其他页面称为

Navigator.of(context)
                .pushNamed('/home');

【讨论】:

请检查这是一个***.com/q/68192605/15610685

以上是关于Flutter 问题:如何导航到另一个页面的主要内容,如果未能解决你的问题,请参考以下文章

Flutter:无法导航到另一个页面

Flutter - 如何在 TabBarView 的主体内导航?

Flutter:从 StreamBuilder 构建器回调内部导航到另一个屏幕

如何在 2.5 版本的新 Flutter 模板上集成底部导航栏?

Flutter BLoC 模式 - 如何在流事件后导航到另一个屏幕?

如何在颤动的主页中导航屏幕?