【问题标题】:I am getting two appBar in flutter app. I am trying to add Drawer widget and TabBar widget in flutter app我在颤振应用程序中获得了两个 appBar。我正在尝试在 Flutter 应用程序中添加 Drawer 小部件和 TabBar 小部件
【发布时间】:2021-11-09 07:50:14
【问题描述】:

main.dart

import 'package:flutter/material.dart';
import 'package:stray_animal_emergencyrescue/signUpPage.dart';
import './commons/commonWidgets.dart';
import 'package:stray_animal_emergencyrescue/loggedIn.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      //title: 'Flutter login UI',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  //String showPasswordText = "Show Password";
  bool obscurePasswordText = true;

  @override
  Widget build(BuildContext context) {

    final passwordField = TextField(
      obscureText: obscurePasswordText,
      decoration: InputDecoration(
          //contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
          hintText: "Password",
          //border: OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)),
          suffixIcon: IconButton(
            icon: new Icon(Icons.remove_red_eye),
            onPressed: () {
              setState(() {
                this.obscurePasswordText = !obscurePasswordText;
              });
            },
          )),
    );

    final loginButon = Material(
      //elevation: 5.0,
      //borderRadius: BorderRadius.circular(30.0),
      color: Colors.blue,
      child: MaterialButton(
        //minWidth: MediaQuery.of(context).size.width,
        //padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
        onPressed: () {
          //print(MediaQuery.of(context).size.width);
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => LogIn()),
          );
        },
        child: Text('Login', textAlign: TextAlign.center),
      ),
    );

    final facebookContinueButton = Material(
      //borderRadius: BorderRadius.circular(30.0),
      color: Colors.blue,
      child: MaterialButton(
        //minWidth: MediaQuery.of(context).size.width,
        //padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
        onPressed: () {
          //print(MediaQuery.of(context).size.width);
        },
        child: Text('Facebook', textAlign: TextAlign.center),
      ),
    );

    final googleContinueButton = Material(
      //borderRadius: BorderRadius.circular(30.0),
      color: Colors.blue,
      child: MaterialButton(
        //minWidth: MediaQuery.of(context).size.width,
        //padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
        onPressed: () {
          //print(MediaQuery.of(context).size.width);
        },
        child: Text('Google ', textAlign: TextAlign.center),
      ),
    );

    final signUpButton = Material(
      //borderRadius: BorderRadius.circular(30.0),
      color: Colors.blue,
      child: MaterialButton(
        //minWidth: MediaQuery.of(context).size.width,
        //padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => FormScreen()),
          );
          //print(MediaQuery.of(context).size.width);
        },
        child: Text('Sign Up ', textAlign: TextAlign.center),
      ),
    );

    return Scaffold(
      appBar: AppBar(
        title: Text("Animal Emergency App"),
      ),
      body: Center(
        child: Container(
          //color: Colors.white,
          child: Padding(
            padding: const EdgeInsets.all(36.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                //SizedBox(height: 45.0),
                getTextFieldWidget(),
                SizedBox(height: 15.0),
                passwordField,
                sizedBoxWidget,
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    facebookContinueButton,
                    SizedBox(width: 5),
                    googleContinueButton,
                    SizedBox(width: 5),
                    loginButon
                  ],
                ),
                /*loginButon,
                signUpButton,*/
                sizedBoxWidget,
                const Divider(
                  color: Colors.black,
                  height: 20,
                  thickness: 1,
                  indent: 20,
                  endIndent: 0,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  //crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    signUpButton
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

loggedIn.dart

import 'package:flutter/material.dart';
import './tabbarviews/emergencyresue/EmergencyHome.dart';
import './tabbarviews/animalcruelty/animalCrueltyHome.dart';
import './tabbarviews/bloodbank/bloodBankHome.dart';

class LogIn extends StatefulWidget {
  @override
  _LogInState createState() => _LogInState();
}

class _LogInState extends State<LogIn> {
  int _selectedIndex = 0;
  static const TextStyle optionStyle =
      TextStyle(fontSize: 30, fontWeight: FontWeight.bold);

  static List<Widget> _widgetOptions = <Widget>[
    EmergencyHome(),
    AnimalCrueltyHome(),
    BloodBankHome()
  ];

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First app bar appearing'),
        actions: <Widget>[
          GestureDetector(
            onTap: () {},
            child: CircleAvatar(
              //child: Text("SC"),
              backgroundImage: AssetImage('assets/images/760279.jpg'),
              //backgroundImage: ,
            ),
          ),
          IconButton(
            icon: Icon(Icons.more_vert),
            color: Colors.white,
            onPressed: () {},
          ),
        ],
      ),
      drawer: Drawer(
        child: ListView(
          children: <Widget>[
            new ListTile(title: Text("Primary")),
            MyListTile(
                "Home",
                false,
                "Your customized News Feed about people you follow, ongoing rescues, nearby activities, adoptions etc.",
                3,
                Icons.home,
                true,
                () {}),
            MyListTile(
                "News & Media Coverage",
                false,
                "News about incidents which need immediate action, changing Laws",
                3,
                Icons.home,
                false,
                () {}),
            MyListTile(
                "Report",
                true,
                "Report cases with evidences anonymously",
                3,
                Icons.announcement,
                false,
                () {}),
            MyListTile(
                "Blood Bank",
                true,
                "Details to donate blood ",
                3,
                Icons.medical_services,
                false,
                () {}),
          ],
        ),
      ),
      body: _widgetOptions[_selectedIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.blue,
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.pets),
            label: 'Emergency Rescue',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.add_alert),
            label: 'Report Cruelty',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.medical_services),
            label: 'Blood Bank',
          ),
          /*BottomNavigationBarItem(
              icon: Icon(Icons.school),
              label: 'Safe Hands',
              backgroundColor: Colors.blue),*/
        ],
        onTap: _onItemTapped,
      ),
    );
  }
}

//Safe Hands
class MyListTile extends StatelessWidget {
  final String title;
  final bool isThreeLine;
  final String subtitle;
  final int maxLines;
  final IconData icon;
  final bool selected;
  final Function onTap;

  MyListTile(this.title, this.isThreeLine, this.subtitle, this.maxLines,
      this.icon, this.selected, this.onTap);

  @override
  Widget build(BuildContext context) {
    return ListTile(
        title: Text(title),
        isThreeLine: isThreeLine,
        subtitle:
            Text(subtitle, maxLines: maxLines, style: TextStyle(fontSize: 12)),
        leading: Icon(icon),
        selected: selected,
        onTap: onTap);
  }
}

EmergencyHome.dart

import 'package:flutter/material.dart';
import './finishedAnimalEmergencies.dart';
import './reportAnimalEmergency.dart';
import './ongoingAnimalEmergencies.dart';

class EmergencyHome extends StatefulWidget {
  @override
  _EmergencyHomeState createState() => _EmergencyHomeState();
}

class _EmergencyHomeState extends State<EmergencyHome> {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          title: Text("Second appBar appearing"),
          bottom: TabBar(
            tabs: [
              Tab(
                //icon: Icon(Icons.more_vert),
                text: "Report",
              ),
              Tab(
                text: "Ongoing",
              ),
              Tab(
                text: "Finished",
              )
            ],
          ),
        ),
        body: TabBarView(
          children: [
            ReportAnimalEmergency(),
            OngoingAnimalEmergencies(),
            FinishedAnimalEmergencies(),
          ],
        ),
      )
    );
  }
}

我面临的问题是两个 appBar,我尝试从loggedIn.dart 中删除appBar,但没有显示抽屉汉堡图标,并且我无法从emergencyHome.dart 中删除appBar,因为我无法添加标签栏。什么是可行的解决方案?请帮助如何按应用和路线构建以轻松管理应用内的导航

【问题讨论】:

  • 有两个 appBars 因为你已经指定了两个应用栏。如果您需要的应​​用栏是第一个应用栏,那为什么要添加第二个应用栏?
  • 我必须添加第二个 AppBar 才能添加 TabBar。 Tabbar 可以放在 AppBar 的 Bottom 属性中。

标签: flutter drawerlayout flutter-routes


【解决方案1】:

从 EmergencyHome.dart 中删除应用栏 这将删除第二个应用程序标题。但是第一个应用栏会有阴影,所以输入elvation:0 所以,这看起来像一个应用栏,现在你的抽屉也可以工作了。

【讨论】:

  • 我不能在没有 AppBar 的情况下放置 TabBar。所以我不能删除 AppBar。
  • 请查看以下答案
【解决方案2】:

你可以在 EmergencyHome.dart 中使用灵活空间

DefaultTabController(
    length: 3,
    child: Scaffold(
      appBar: AppBar(
        flexibleSpace: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
            TabBar(
              tabs: [
                Tab(
                  //icon: Icon(Icons.more_vert),
                  text: "Report",
                ),
                Tab(
                  text: "Ongoing",
                ),
                Tab(
                  text: "Finished",
                )
              ],
            )
          ],
        ),
      ),
      body: TabBarView(
        children: [
        ReportAnimalEmergency(),
        OngoingAnimalEmergencies(),
        FinishedAnimalEmergencies(),
        ],
      ),
    )
);

【讨论】:

    【解决方案3】:

    您不想制作两个 appbar 来获取抽屉属性。使用 DefaultTabController 然后在里面你可以使用scaffold.so,你可以在里面有drawer: Drawer(),你也可以通过TabBar 获得一个appbar,因为它是bottom。 根据您的用例,这最适合您。

    我会把完整的代码放在下面,你可以复制它。

    
    void main() {
      runApp(const TabBarDemo());
    }
    
    class TabBarDemo extends StatelessWidget {
      const TabBarDemo({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: DefaultTabController(
            length: 3,
            child: Scaffold(
              drawer: Drawer(),
              appBar: AppBar(
                bottom: const TabBar(
                  tabs: [
                   Tab(
                      text: "report",
                    ),
                    Tab(text: "ongoing"),
                    Tab(text: "completed"),
                  ],
                ),
                title: const Text('Tabs Demo'),
              ),
              body: const TabBarView(
                children: [
                  Icon(Icons.directions_car),
                  Icon(Icons.directions_transit),
                  Icon(Icons.directions_bike),
                ],
              ),
            ),
          ),
        );
      }
    }
    

    输出

    【讨论】:

    • 在我的 main.dart 中,我有登录和注册按钮。只有在用户单击登录后,用户才会被定向到 loggedIn.dart。请检查我有问题的 main.dart 文件并建议我一个解决方案。
    • 是的,您之前可以有一个登录页面,并在登录按钮中使用按下功能。 onPressed: () { //print(MediaQuery.of(context).size.width); Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) =&gt; //here you will go to the new page ), ); },
    • 这是否解决了您的问题
    • 我是初学者,我用flexibleSpace解决了我的问题,但即使我仍然在导航和路由上挣扎,我需要改变整个项目结构。所以我的问题还没有解决。
    • 在此处添加有关导航和路由的问题。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-04-01
    • 2022-10-04
    • 2019-11-25
    • 2021-09-12
    • 2021-03-26
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    相关资源
    最近更新 更多