根据当前查看的页面更改AppBar的颜色和文本 [英] Changing the color and text of AppBar based on the currently viewed page

查看:79
本文介绍了根据当前查看的页面更改AppBar的颜色和文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个TabBarView,可在应用程序的页面之间导航。有没有一种方法可以根据当前查看的页面来更改/替代主AppBar的文本和颜色,而不是分别为每个页面创建一个AppBar?

I have a TabBarView that navigates between the pages in my app. Is there a way to change/override the text and the color of the main AppBar based on the currently viewed page, instead of creating an AppBar for each page separately?

此设置页面的方式是

我的路线在主要功能中定义如下:

My routes are defined in the main function as follows:

routes: <String, WidgetBuilder>{
            "/Home": (BuildContext context) => new first.Home(),
            "/Support": (BuildContext context) => new second.Support(),

          }

标签类

        class Tabs extends StatefulWidget {

          @override
          TabsState createState() => new TabsState();
        }

    class TabsState extends State<Tabs> with SingleTickerProviderStateMixin {
      TabController controller;

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

        controller = new TabController(length: 5, vsync: this);

      }

      @override
      void dispose() {
        controller.dispose();
        super.dispose();

      }
      @override
      Widget build(BuildContext context) {

      return new Scaffold(
        appBar: new AppBar(
          centerTitle: true,
          title: new Text('App'), backgroundColor: Colors.blue,
          bottom: new TabBar(
              controller: controller,
              tabs: <Tab>[
                new Tab (icon: new Icon(Icons.home), text: 'Home',),
                            new Tab (icon: new Icon(Icons.mail), text:'Support'),
              ]),
        ),
        body: new TabBarView(
          controller: controller,
          children: <Widget>[
            new first.Home(),
            new second.Support(),

          ],
        ),
      );
    }      


推荐答案

我修改了此代码以添加支持文本和颜色更改

I modified this code to add support for text and color change i guess

https://flutter.io/catalog/samples/tabbed-app-bar/

我为代码的丑陋表示歉意。我所做的就是将所有类都更改为有状态的小部件,添加一个setstate图标选择器,然后更改小部件,以便进行onPressed回调

I apologize for the ugliness for the code. All I did was change all the classes to stateful widget, add an setstate icon selector, change the widget so there is an onPressed callback

  import 'package:flutter/material.dart';

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

    // This widget is the home page of your application. It is stateful,
    // meaning that it has a State object (defined below) that contains
    // fields that affect how it looks.

    // This class is the configuration for the state. It holds the
    // values (in this case the title) provided by the parent (in this
    // case the App widget) and used by the build method of the State.
    // Fields in a Widget subclass are always marked "final".

    final String title;
    @override
    TabbedAppBarSample createState() => new TabbedAppBarSample();
  }
  class TabbedAppBarSample extends State<MainApp> {
    Choice _choice;
    initState(){
      super.initState();
      _choice = choices[0];
    }
    void _select(var c){
      setState((){
        _choice = c;
      });

    }

    @override
    Widget build(BuildContext context) {
      return new MaterialApp(
        home: new DefaultTabController(

          length: choices.length,
          child: new Scaffold(
            appBar: new AppBar(
              //dynamically create appbar colors
              backgroundColor: new Color(_choice.color),
              title: new Text(_choice.title),
              bottom: new TabBar(
                isScrollable: true,
                tabs: choices.map((Choice choice) {
                   //change to iconbutton
                  return new IconButton(
                    icon: new Icon(choice.icon),
                    onPressed: (){_select(choice);},
                  );
                }).toList(),
              ),
            ),
            body:
            new TabBarView(
              children: choices.map((Choice choice) {
                return new Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: new ChoiceCard(choice: choice),
                );
              }).toList(),
            ),
          ),
        ),
      );
    }
  }

  class Choice {
    const Choice({ this.title, this.icon, this.color});
    final String title;
    final IconData icon;
    final num color;
  }

  const List<Choice> choices = const <Choice>[
    const Choice(title: 'CAR', icon: Icons.directions_car, color:  0xFFE0F7FA),
    const Choice(title: 'BICYCLE', icon: Icons.directions_bike, color: 0x00ff0000),
    const Choice(title: 'BOAT', icon: Icons.directions_boat, color: 0xFF42A5F5),
    const Choice(title: 'BUS', icon: Icons.directions_bus, color: 0x0),
    const Choice(title: 'TRAIN', icon: Icons.directions_railway, color: 0xFFEFFFFF),
    const Choice(title: 'WALK', icon: Icons.directions_walk, color: 0x0000ff00),
  ];
  class ChoiceCard extends StatefulWidget {
    ChoiceCard({Key key, this.choice}) : super(key: key);
    final Choice choice;
    @override
    _ChoiceCard createState() => new _ChoiceCard();
  }
  class _ChoiceCard extends State<ChoiceCard> {


    @override
    Widget build(BuildContext context) {
      final TextStyle textStyle = Theme.of(context).textTheme.display1;

      return new Card(
        color: Colors.white,
        child: new Center(
          child: new Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              new Icon(widget.choice.icon, size: 128.0, color: textStyle.color),
              new Text(widget.choice.title, style: textStyle),
            ],
          ),
        ),
      );
    }
  }

  void main() {
    runApp(new MainApp());
  }

我有点恼火,因为我上面的代码类似于op的实际答案需要。上面我的代码与操作员想要的唯一区别是,我将on更改添加到了tabcontroller而不是按钮本身

I am a bit annoyed because my code above is similar to actual answer the op needed. The only difference between my code above and what the op wanted is that I added the on change to the tabcontroller instead of the button itself

这里是代码

 import 'package:flutter/material.dart';
 void main() {
   runApp(new MyApp());
 }
 class MyApp extends StatelessWidget{
   Widget build(BuildContext context) {
     return new MaterialApp(
       title: 'Nothing',
       theme: new ThemeData(
         primarySwatch: Colors.blue,
       ),
       home: new Tabs(),
     );
   }

 }
 class Tabs extends StatefulWidget {
   @override
   TabsState createState() => new TabsState();
 }
 class TabsState extends State<Tabs> with SingleTickerProviderStateMixin {
   TabController controller;
   //create internal state
   Choice _choice;
   @override
   void initState() {
     super.initState();
     //try to make the length to
     controller = new TabController(length: 5, vsync: this);
     //add listener to add change index callback
     //https://docs.flutter.io/flutter/material/TabController-class.html
     controller.addListener(_select);
     _choice = choices[0];

   }
   @override
   void dispose() {
     controller.dispose();
     super.dispose();
   }

   void _select(){
     setState((){
       _choice = choices[controller.index];
     });

   }
   @override
   Widget build(BuildContext context) {
     return new Scaffold(
         appBar: new AppBar(
           centerTitle: true,
           title: new Text(_choice.title), backgroundColor: new Color(_choice.color),
           bottom: new TabBar(
               controller: controller,
               tabs: <Tab>[
                 new Tab( icon: new Icon(choices[0].icon), text: 'Home',),
                 new Tab (icon: new Icon(choices[1].icon), text:'Support'),
               ]),
         ),
         body: new TabBarView(
           controller: controller,
           children: <Widget>[
             //dummy page
             new MyHomePage(),
             new  Center( child: new Text('dummy page 2')),

           ],
         ),
     );
   }
 }
 class Choice {
   const Choice({ this.title, this.icon, this.color});
   final String title;
   final IconData icon;
   final num color;
 }
 //create a list
 const List<Choice> choices = const <Choice>[
   const Choice(title: 'Home', icon: Icons.home, color:  0x0),
   const Choice(title: 'Support', icon: Icons.mail, color: 0xFF42A5F5),

 ];


 class MyHomePage extends StatefulWidget {
   @override
   _MyHomePageState createState() => new _MyHomePageState();
 }
 class _MyHomePageState extends State<MyHomePage> {
   @override
   Widget build(BuildContext context) {
     return new Center(
       child: new Text('dummy page'),
     );
   }
 }

这篇关于根据当前查看的页面更改AppBar的颜色和文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆