底部导航栏在登录时消失,但是在我转到另一个页面并返回时又返回?

如何解决底部导航栏在登录时消失,但是在我转到另一个页面并返回时又返回?

我正在尝试创建一个应用,该应用将向用户显示带有产品的通用首页,并为他们提供导航到帐户页面的选项,如果未登录,则将在其中显示登录/注册页面或如果他们已登录,则将向他们显示其个人资料。

我设法使登录/退出部分正常工作,但是当我登录并导航到个人资料页面时,我的底部导航栏消失了。但是,当我导航到另一个页面并返回时,它会重新出现。

这是我的home.dart文件,用于控制我的应用的导航:

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  PageController _pageController = PageController();
  List<Widget> _screens = [HomePage(),InboxPage(),AccountController()];


  int _selectedIndex = 0;

  void _onPageChanged(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  void _onItemTapped(int selectedIndex) {
    _pageController.jumpToPage(selectedIndex);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
        controller: _pageController,children: _screens,onPageChanged: _onPageChanged,physics: NeverScrollableScrollPhysics(),),bottomNavigationBar: BottomNavigationBar(onTap: _onItemTapped,items: [
        BottomNavigationBarItem(
          icon: Icon(
            Icons.home,color: _selectedIndex == 0 ? Colors.blueAccent : Colors.grey,title: Text(
            'Home',style: TextStyle(
              color: _selectedIndex == 0 ? Colors.blueAccent : Colors.grey,BottomNavigationBarItem(
          icon: Icon(
            Icons.email,color: _selectedIndex == 1 ? Colors.blueAccent : Colors.grey,title: Text(
            'Inbox',style: TextStyle(
              color: _selectedIndex == 1 ? Colors.blueAccent : Colors.grey,BottomNavigationBarItem(
          icon: Icon(
            Icons.account_circle,color: _selectedIndex == 2 ? Colors.blueAccent : Colors.grey,title: Text(
            'Account',style: TextStyle(
              color: _selectedIndex == 2 ? Colors.blueAccent : Colors.grey,]),);
  }
}

我的accountcontroller.dart代码可帮助确定用户是否已登录:

class AccountController extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final AuthService auth = Provider.of(context).auth;
    return StreamBuilder(
        stream: auth.onAuthStateChanged,builder: (context,AsyncSnapshot<String> snapshot) {
          if (snapshot.connectionState == ConnectionState.active) {
            final bool signedIn = snapshot.hasData;
            return signedIn ? ProfileView() : SignUpPage();
          }
          return CircularProgressIndicator();
        });
  }
}

我的个人资料view.dart:

class ProfileView extends StatefulWidget {

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

class _ProfileViewState extends State<ProfileView> {


  @override
  Widget build(BuildContext context) {
    return
      Scaffold(
        appBar: PreferredSize(
            preferredSize: const Size.fromHeight(80),child: MainAppBar(
              text: 'Account',)),body: SingleChildScrollView(
        child: Column(
        children: <Widget>[
          Text('Account Page'),showSignOut(context),goToHomepage(context),],);
  }
}

Widget showSignOut(context) {
  return RaisedButton(
      child: Text('Sign Out'),onPressed: () async {
        try {
          await Provider.of(context).auth.signOut();
          Navigator.pushNamed(context,'/homepage');
          print('Signed Out');
        } catch (e) {
          print(e);
        }
      });
}

Widget goToHomepage(context) {
  return RaisedButton(
      child: Text('Go to homepage'),onPressed: () async {
        try {
          Navigator.pushNamed(context,'/homepage');
        } catch (e) {
          print(e);
        }
      });
}

最后是我的signup.dart文件,其中包含我的注册/登录代码:

enum AuthFormType { signIn,signUp }

class SignUpPage extends StatefulWidget {
  final AuthFormType authFormType;

  SignUpPage({Key key,this.authFormType}) : super(key: key);

  @override
  _SignUpPageState createState() =>
      _SignUpPageState(authFormType: this.authFormType);
}

class _SignUpPageState extends State<SignUpPage> {
  AuthFormType authFormType;

  _SignUpPageState({this.authFormType});

  final formKey = GlobalKey<FormState>();
  String _firstName,_lastName,_email,_confirmEmail,_password,_confirmPassword,_dateOfBirth;

  bool validate() {
    final form = formKey.currentState;
    form.save();
    if (form.validate()) {
      form.save();
      print('true');
      return true;
    } else {
      print('false');
      return false;
    }
  }

  void switchFormState(String state) {
    formKey.currentState.reset();
    if (state == 'signIn') {
      setState(() {
        authFormType = AuthFormType.signIn;
      });
    } else {
      setState(() {
        authFormType = AuthFormType.signUp;
      });
    }
  }

  void submit() async {
    final CollectionReference userCollection =
        Firestore.instance.collection('UserData');

    if (validate()) {
      try {
        final auth = Provider.of(context).auth;
        if (authFormType == AuthFormType.signIn) {
          String uid = await auth.signInWithEmailAndPassword(_email,_password);
          print("Signed In with ID $uid");
          Navigator.of(context).pushReplacementNamed('/home');
        } else {
          String uid = await auth.createUserWithEmailAndPassword(
            _email,);
          userCollection.document(uid).setData({
            'First Name': _firstName,'Last Name': _lastName,'Date of Birth': _dateOfBirth
          });
          print("Signed up with New ID $uid");
          Navigator.of(context).pushReplacementNamed('/home');
        }
      } catch (e) {
        print(e);
      }
    }
  }

  DateTime selectedDate = DateTime.now();
  TextEditingController _date = new TextEditingController();

  Future<Null> _selectDate(BuildContext context) async {
    DateFormat formatter =
        DateFormat('dd/MM/yyyy'); //specifies day/month/year format

    final DateTime picked = await showDatePicker(


        context: context,initialDate: selectedDate,firstDate: DateTime(1901,1),builder: (BuildContext context,Widget child) {
          return Theme(
            data: ThemeData.light().copyWith(
              colorScheme: ColorScheme.light(
                primary: kPrimaryColor,onPrimary: Colors.black,buttonTheme: ButtonThemeData(
                colorScheme: Theme.of(context)
                    .colorScheme
                    .copyWith(primary: Colors.black),child: child,);
        },lastDate: DateTime(2100));

    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
        _date.value = TextEditingValue(
            text: formatter.format(
                picked)); //Use formatter to format selected date and assign to text field
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: PreferredSize(
            preferredSize: const Size.fromHeight(80),child: MainAppBar(
              text: buildAppBarText(),body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(12.0),child: Center(
              child: Container(
                child: Column(
                  children: <Widget>[
                    Align(
                      child: Text(buildTitleText(),style: AppBarTextStyle),Container(
                      padding: EdgeInsets.only(top: 10),Padding(
                      padding: const EdgeInsets.all(20.0),child: Form(
                          key: formKey,child: Column(
                            children: buildInputs() + buildSwitchText(),));
  }

  buildHeaderText() {
    String _headerText;
    if (authFormType == AuthFormType.signUp) {
      _headerText = "Don't have an account?";
    } else {
      _headerText = "Already have an account?";
    }
    return _headerText;
  }

  List<Widget> buildInputs() {
    List<Widget> textFields = [];

    DateFormat dateFormat = DateFormat("yyyy-MM-dd HH:mm:ss");

    if (authFormType == AuthFormType.signIn) {
      textFields.add(TextFormField(
          style: TextStyle(
            fontSize: 12.0,decoration: buildSignUpInputDecoration('Email'),validator: SignInEmailValidator.validate,onSaved: (value) => _email = value.trim()));
      textFields.add(SizedBox(
        height: 15,));
      textFields.add(
        TextFormField(
          style: TextStyle(
            fontSize: 12.0,decoration: buildSignUpInputDecoration('Password'),obscureText: true,validator: SignInPasswordValidator.validate,onSaved: (value) => _password = value.trim(),);
    } else {
      textFields.clear();
      //if we're in the sign up state,add name
      // add email & password
      textFields.add(TextFormField(
        style: TextStyle(
          fontSize: 12.0,decoration: buildSignUpInputDecoration('First Name'),validator: NameValidator.validate,onSaved: (value) => _firstName = value,));
      textFields.add(SizedBox(
        height: 15,));
      textFields.add(TextFormField(
        style: TextStyle(
          fontSize: 12.0,decoration: buildSignUpInputDecoration('Last Name'),onSaved: (value) => _lastName = value,decoration: buildSignUpInputDecoration('Email Address'),onSaved: (value) => _email = value.trim(),decoration: buildSignUpInputDecoration('Confirm Email Address'),onSaved: (value) => _confirmEmail = value,validator: (confirmation) {
          return confirmation == _email
              ? null
              : "Confirm Email Address should match email address";
        },onSaved: (value) => _password = value,));
      textFields.add(TextFormField(
          style: TextStyle(
            fontSize: 12.0,decoration: buildSignUpInputDecoration('Confirm Password'),onSaved: (value) => _confirmPassword = value,validator: (confirmation) {
            return confirmation == _password
                ? null
                : "Confirm Password should match password";
          }));
      textFields.add(SizedBox(
        height: 15,));
      textFields.add(GestureDetector(
        onTap: () => _selectDate(context),child: AbsorbPointer(
          child: TextFormField(
            style: TextStyle(fontSize: 12.0),controller: _date,keyboardType: TextInputType.datetime,decoration: InputDecoration(
              isDense: true,fillColor: Colors.white,hintText: 'Date of Birth',filled: true,enabledBorder: OutlineInputBorder(
                borderSide: BorderSide(width: 0.0),contentPadding:
                  const EdgeInsets.only(left: 14.0,bottom: 10.0,top: 10.0),onSaved: (value) => _dateOfBirth = value,));

      textFields.add(SizedBox(
        height: 15,));
    }
    return textFields;
  }

  List<Widget> buildSwitchText() {
    String _switchButtonTextPart1,_switchButtonTextPart2,_newFormState;

    if (authFormType == AuthFormType.signIn) {
      _switchButtonTextPart1 = "Haven't got an account? ";
      _switchButtonTextPart2 = 'Sign Up';
      _newFormState = 'signUp';
    } else {
      _switchButtonTextPart1 = 'Already have an account? ';
      _switchButtonTextPart2 = 'Sign In';
      _newFormState = 'signIn';
    }
    return [
      SizedBox(height: 5.0),Container(
        width: MediaQuery.of(context).size.height * 0.7,child: RaisedButton(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(5.0),color: kPrimaryColor,textColor: Colors.black,child: Padding(
              padding: const EdgeInsets.all(8.0),child: Text(
                buildTitleText(),style: TextStyle(fontFamily: FontNameDefault,fontSize: 15.0),onPressed: submit),SizedBox(
        height: 5.0,RichText(
        text: TextSpan(
            style: TextStyle(
              fontFamily: FontNameDefault,color: Colors.black,fontSize: 12.0,children: <TextSpan>[
              TextSpan(text: _switchButtonTextPart1),TextSpan(
                  text: _switchButtonTextPart2,style: TextStyle(
                      decoration: TextDecoration.underline,fontSize: 12.0),recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      switchFormState(_newFormState);
                    })
            ]),];
  }

  String buildAppBarText() {
    String _switchAppBarHeader;

    if (authFormType == AuthFormType.signIn) {
      _switchAppBarHeader = "Already have an account?";
    } else {
      _switchAppBarHeader = "Don't have an account?";
    }
    return _switchAppBarHeader;
  }

  String buildTitleText() {
    String _switchTextHeader;

    if (authFormType == AuthFormType.signIn) {
      _switchTextHeader = "Sign In";
    } else {
      _switchTextHeader = "Sign Up";
    }
    return _switchTextHeader;
  }
}


InputDecoration buildSignUpInputDecoration(String hint) {
  return InputDecoration(
    isDense: true,hintText: hint,enabledBorder: OutlineInputBorder(
      borderSide: BorderSide(width: 0.0),contentPadding: const EdgeInsets.only(left: 14.0,);
}

有什么想法吗?

解决方法

HomePage(),InboxPage()和AccountController()位于您的家庭小部件中,其中包含bottomNavigationBar。 您的个人资料页面和注册页面是具有自己的支架的不同页面。 您必须创建一个中央“索引”窗口小部件,其中包含每个子页面和导航栏。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-