Flutter - 如何在AppBar不存在时设置状态栏颜色

时间:2018-05-24 05:44:15

标签: dart flutter statusbar

如何在AppBar不存在时设置状态栏颜色。

  

我试过这个但没有用。

{{1}}

输出如下:

enter image description here

18 个答案:

答案 0 :(得分:43)

首先,导入services软件包:

import 'package:flutter/services.dart';

接下来,只需将其放入应用程序的构建功能中即可

SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark.copyWith(
  statusBarColor: Colors.blue, //or set color with: Color(0xFF0000FF)
));

此外,您可以设置有用的变量,例如:statusBarIconBrightnesssystemNavigationBarColorsystemNavigationBarDividerColor

答案 1 :(得分:9)

如果您在AppBar的source code上抢劫了,可以看到他们使用了AnnotatedRegion小部件。

据我了解,当包装在其中的小部件被状态栏/导航栏覆盖时,此小部件会自动设置状态栏/导航栏颜色。

您可以像这样包装小部件:

import 'package:flutter/services.dart';

...    

Widget build(BuildContext context) {
   return Scaffold(
      body: AnnotatedRegion<SystemUiOverlayStyle>(
         value: SystemUiOverlayStyle.light,                
         child: ...,
      ),
   );
}

答案 2 :(得分:4)

在Android上,在调用super.onCreate(savedInstanceState)之后,将以下内容添加到 MainActivity.java 中的onCreate;

  

getWindow()setStatusBarColor(00000000);

或者您可以使用flutter_statusbarcolor插件

   changeStatusColor(Color color) async {
    try {
      await FlutterStatusbarcolor.setStatusBarColor(color);
    } on PlatformException catch (e) {
      print(e);
    }
  }

Sample project

答案 3 :(得分:4)

在搜索SystemChrome时,我发现了这一点:https://docs.flutter.io/flutter/services/SystemChrome/setSystemUIOverlayStyle.html

示例代码的正上方是一个关于AppBar.brightness的段落。

您应该应该能够像这样添加一个AppBar:

Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
    return new Scaffold(
        appBar: new AppBar(
            title: new Text('Nice title!'),
            brightness: Brightness.light,
        ),
        body: new Container(
        color: UniQueryColors.colorBackground,
        child: new ListView.builder(
           itemCount: 7,
           itemBuilder: (BuildContext context, int index){
             if (index == 0){
               return addTopInfoSection();
             }
           },
        ),
       ),
    );
}

此处提供有关Brightness的信息

答案 4 :(得分:3)

我尝试了很多方法,但是没有用。我发现了另一种方法,使用safeArea,AnnotatedRegion和Scaffold

AnnotatedRegion(
  // status icon and text color, dark:black  light:white
  value: SystemUiOverlayStyle.dark,
  child: Scaffold(
     // statusbar color
     backgroundColor: Colors.white,
     body : SafeArea(****)
  )
}

该代码实现了白色状态栏和黑色文本

答案 5 :(得分:2)

Widget build(BuildContext context) {

    return new Scaffold(
        body: new Container(
            color: UniQueryColors.colorBackground,

    /* Wrapping ListView.builder with MediaQuery.removePadding() removes the default padding of the ListView.builder() and the status bar takes the color of the app background */

        child: MediaQuery.removePadding(
         removeTop: true,
         context: context,
        child: ListView.builder(
           itemCount: 7,
           itemBuilder: (BuildContext context, int index){
             if (index == 0){
               return addTopInfoSection();
             }
           },
        ),
       ),
      ),
    );
}

答案 6 :(得分:1)

状态栏颜色由Android系统呈现。是否可以通过Flutter设置是有争议的:How to make Android status bar light in Flutter

但是,您可以通过编辑主题更改Android特定代码中的状态栏颜色:How to change the status bar color in android

对于iOS,您必须查看他们的文档 - 我不熟悉该平台。

实际上有两个Dart库,一个用于设置light/dark theme of the statusbar,另一个用于setting the colour。我还没有使用过,但很明显其他人遇到了你所面临的同样问题并最终开发了自己的软件包。

答案 7 :(得分:1)

最好的状态栏,例如没有AppBar()的默认材质设计主题

 Container(width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).padding.top, color: Theme.of(context).accentColor)

答案 8 :(得分:0)

您可以使用SystemUiOverlayStyle

 Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
              backgroundColor: Colors.white,
              elevation: 0.0,
              systemOverlayStyle: SystemUiOverlayStyle(
                statusBarColor: Colors.white,
                statusBarBrightness: Brightness.dark,
                statusBarIconBrightness: Brightness.dark,
              )),
          body:.....

答案 9 :(得分:0)

如果您不想使用应用程序栏,那么

appBar: AppBar(
      elevation: 0,
      backgroundColor: Colors.white, # status bar color
      toolbarHeight: 0,
      brightness: Brightness.light # or Brightness.dark

答案 10 :(得分:0)

在主要功能中使用以下命令更改所有视图/屏幕的状态栏颜色。即使没有应用程序栏也可以使用。

WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
  statusBarIconBrightness: Brightness.dark, // this will change the brightness of the icons
  statusBarColor: Colors.white, // or any color you want
));

答案 11 :(得分:0)

如果要用作MaterialApp主题中的默认模板,只需添加此内容:

appBarTheme: AppBarTheme(brightness: Brightness.light)

结果将如下所示:

return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        appBarTheme: AppBarTheme(brightness: Brightness.light),  <========
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ...,
    );

答案 12 :(得分:0)

只需将其添加到您的构建函数或主函数中即可。

import 'package:flutter/services.dart';

Widget build(BuildContext context) {
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
  ...
}

答案 13 :(得分:0)

您可以使用cognito:groups类来更改状态栏和导航栏的颜色。 首次导入

SystemChrome

此后,您需要添加以下几行(放置这些行的更好的位置是您的import 'package:flutter/services.dart'; 方法中)

main()

答案 14 :(得分:0)

使用EmptyAppBar,并使用一些代码来恢复色彩,如AppBar

class EmptyAppBar  extends StatelessWidget implements PreferredSizeWidget {
  static const double _defaultElevation = 4.0;
  @override
  Widget build(BuildContext context) {
    final ThemeData themeData = Theme.of(context);
    final AppBarTheme appBarTheme = AppBarTheme.of(context);
    final Brightness brightness = appBarTheme.brightness
        ?? themeData.primaryColorBrightness;
    final SystemUiOverlayStyle overlayStyle = brightness == Brightness.dark
        ? SystemUiOverlayStyle.light
        : SystemUiOverlayStyle.dark;

    return Semantics(
      container: true,
      child: AnnotatedRegion<SystemUiOverlayStyle>(
        value: overlayStyle,
        child: Material(
          color: appBarTheme.color
              ?? themeData.primaryColor,
          elevation: appBarTheme.elevation
              ?? _defaultElevation,
          child: Semantics(
            explicitChildNodes: true,
            child: Container(),
          ),
        ),
      ),
    );
  }
  @override
  Size get preferredSize => Size(0.0,0.0);
}

答案 15 :(得分:0)

您应该通过两种方式解决此问题:

  1. 您没有设置appBar,而是以这种方式编写:
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark.copyWith(
  statusBarColor: Colors.black, 
));

SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light.copyWith(
  statusBarColor: Colors.white, 
));
  1. 您始终设置appBar,因此应设置appBar,但不要设置代码:
Scaffold(
  appBar: AppBar(
    brightness: Brightness.light,
  )
)

Scaffold(
  appBar: AppBar(
    brightness: Brightness.dark,
  )
)

答案 16 :(得分:0)

因为已经提到了解决方案,所以我正在以另一种方式来实现它。遵循的方法是删除 AppBar 并使用 Container 小部件更改状态栏的颜色。

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Test',
      home: Scaffold(
        primary: true,
        appBar: EmptyAppBar(),
        body: MyScaffold(),
      ),
    ),
  );
}

class MyScaffold extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(
        'Test',
      ),
    );
  }
}

class EmptyAppBar extends StatelessWidget implements PreferredSizeWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.black,
    );
  }

  @override
  Size get preferredSize => Size(0.0, 0.0);
}
  • 这里我正在使用 EmptyAppBar 类删除 AppBar ,该类默认情况下存在于 Scaffold
  • EmptyAppBar 类中,我们可以在容器小部件中选择所需的颜色。
  • 之后,您将拥有自己的自定义 MyScaffold 类,用于创建窗口小部件。在我的代码中,我创建了一个文本。

参考:GitHub Issue

答案 17 :(得分:-1)

Here You can use flutter flutter_statusbar_manager 1.0.2 lib


Flutter Statusbar Manager, lets you control the status bar color, style (theme), visibility, and translucent properties across iOS and Android. With some added bonus for Android to control the Navigation Bar.


import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_statusbar_manager/flutter_statusbar_manager.dart';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  MyApp();

  factory MyApp.forDesignTime() {
    // TODO: add arguments
    return new MyApp();
  }

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

class _MyAppState extends State<MyApp> {
  double _statusBarHeight = 0.0;
  bool _statusBarColorAnimated = false;
  Color _statusBarColor = Colors.black;
  double _statusBarOpacity = 1.0;
  bool _statusBarHidden = false;
  StatusBarAnimation _statusBarAnimation = StatusBarAnimation.NONE;
  StatusBarStyle _statusBarStyle = StatusBarStyle.DEFAULT;
  bool _statusBarTranslucent = false;
  bool _loadingIndicator = false;
  bool _fullscreenMode = false;

  bool _navBarColorAnimated = false;
  Color _navBarColor = Colors.black;
  NavigationBarStyle _navBarStyle = NavigationBarStyle.DEFAULT;

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

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    double statusBarHeight;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      statusBarHeight = await FlutterStatusbarManager.getHeight;
    } on PlatformException {
      statusBarHeight = 0.0;
    }
    if (!mounted) return;

    setState(() {
      _statusBarHeight = statusBarHeight;
    });
  }

  Widget renderTitle(String text) {
    final textStyle = TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold);
    return Text(text, style: textStyle);
  }

  void colorBarChanged(Color val) {
    this.setState(() {
      _statusBarColor = val;
    });
    updateStatusBar();
  }

  void updateStatusBar() {
    FlutterStatusbarManager.setColor(
        _statusBarColor.withOpacity(_statusBarOpacity),
        animated: _statusBarColorAnimated);
  }

  void statusBarAnimationChanged(StatusBarAnimation val) {
    this.setState(() {
      _statusBarAnimation = val;
    });
  }

  void statusBarStyleChanged(StatusBarStyle val) {
    this.setState(() {
      _statusBarStyle = val;
    });
    FlutterStatusbarManager.setStyle(val);
  }

  void colorNavBarChanged(Color val) {
    this.setState(() {
      _navBarColor = val;
    });
    updateNavBar();
  }

  void updateNavBar() {
    FlutterStatusbarManager.setNavigationBarColor(_navBarColor,
        animated: _navBarColorAnimated);
  }

  void navigationBarStyleChanged(NavigationBarStyle val) {
    this.setState(() {
      _navBarStyle = val;
    });
    FlutterStatusbarManager.setNavigationBarStyle(val);
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Statusbar Manager example'),
        ),
        body: new Container(
          child: new Scrollbar(
            child: new ListView(
              padding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 20.0),
              children: <Widget>[
                renderTitle("Status Bar Height: $_statusBarHeight"),
                Divider(height: 25.0),
                renderTitle("Status Bar Color:"),
                SwitchListTile(
                  value: _statusBarColorAnimated,
                  title: new Text("Animated:"),
                  onChanged: (bool value) {
                    this.setState(() {
                      _statusBarColorAnimated = value;
                    });
                  },
                ),
                Text("Color:"),
                RadioListTile(
                    value: Colors.black,
                    title: Text("Black"),
                    onChanged: colorBarChanged,
                    dense: true,
                    groupValue: _statusBarColor),
                RadioListTile(
                    value: Colors.orange,
                    title: Text("Orange"),
                    onChanged: colorBarChanged,
                    dense: true,
                    groupValue: _statusBarColor),
                RadioListTile(
                    value: Colors.greenAccent,
                    title: Text("Green"),
                    onChanged: colorBarChanged,
                    dense: true,
                    groupValue: _statusBarColor),
                RadioListTile(
                    value: Colors.white30,
                    title: Text("White"),
                    onChanged: colorBarChanged,
                    dense: true,
                    groupValue: _statusBarColor),
                Text("Opacity:"),
                Slider(
                  value: _statusBarOpacity,
                  min: 0.0,
                  max: 1.0,
                  onChanged: (double val) {
                    this.setState(() {
                      _statusBarOpacity = val;
                    });
                    updateStatusBar();
                  },
                ),
                Divider(height: 25.0),
                renderTitle("Status Bar Hidden:"),
                SwitchListTile(
                  title: new Text("Hidden:"),
                  value: _statusBarHidden,
                  onChanged: (bool val) {
                    this.setState(() {
                      _statusBarHidden = val;
                    });
                    FlutterStatusbarManager.setHidden(_statusBarHidden,
                        animation: _statusBarAnimation);
                  },
                ),
                Text("Animation:"),
                RadioListTile(
                    value: StatusBarAnimation.NONE,
                    title: Text("NONE"),
                    onChanged: statusBarAnimationChanged,
                    dense: true,
                    groupValue: _statusBarAnimation),
                RadioListTile(
                    value: StatusBarAnimation.FADE,
                    title: Text("FADE"),
                    onChanged: statusBarAnimationChanged,
                    dense: true,
                    groupValue: _statusBarAnimation),
                RadioListTile(
                    value: StatusBarAnimation.SLIDE,
                    title: Text("SLIDE"),
                    onChanged: statusBarAnimationChanged,
                    dense: true,
                    groupValue: _statusBarAnimation),
                Divider(height: 25.0),
                renderTitle("Status Bar Style:"),
                RadioListTile(
                    value: StatusBarStyle.DEFAULT,
                    title: Text("DEFAULT"),
                    onChanged: statusBarStyleChanged,
                    dense: true,
                    groupValue: _statusBarStyle),
                RadioListTile(
                    value: StatusBarStyle.LIGHT_CONTENT,
                    title: Text("LIGHT_CONTENT"),
                    onChanged: statusBarStyleChanged,
                    dense: true,
                    groupValue: _statusBarStyle),
                RadioListTile(
                    value: StatusBarStyle.DARK_CONTENT,
                    title: Text("DARK_CONTENT"),
                    onChanged: statusBarStyleChanged,
                    dense: true,
                    groupValue: _statusBarStyle),
                Divider(height: 25.0),
                renderTitle("Status Bar Translucent:"),
                SwitchListTile(
                  title: new Text("Translucent:"),
                  value: _statusBarTranslucent,
                  onChanged: (bool val) {
                    this.setState(() {
                      _statusBarTranslucent = val;
                    });
                    FlutterStatusbarManager
                        .setTranslucent(_statusBarTranslucent);
                  },
                ),
                Divider(height: 25.0),
                renderTitle("Status Bar Activity Indicator:"),
                SwitchListTile(
                  title: new Text("Indicator:"),
                  value: _loadingIndicator,
                  onChanged: (bool val) {
                    this.setState(() {
                      _loadingIndicator = val;
                    });
                    FlutterStatusbarManager
                        .setNetworkActivityIndicatorVisible(_loadingIndicator);
                  },
                ),
                Divider(height: 25.0),
                renderTitle("Navigation Bar Color:"),
                SwitchListTile(
                  value: _navBarColorAnimated,
                  title: new Text("Animated:"),
                  onChanged: (bool value) {
                    this.setState(() {
                      _navBarColorAnimated = value;
                    });
                  },
                ),
                Text("Color:"),
                RadioListTile(
                    value: Colors.black,
                    title: Text("Black"),
                    onChanged: colorNavBarChanged,
                    dense: true,
                    groupValue: _navBarColor),
                RadioListTile(
                    value: Colors.orange,
                    title: Text("Orange"),
                    onChanged: colorNavBarChanged,
                    dense: true,
                    groupValue: _navBarColor),
                RadioListTile(
                    value: Colors.greenAccent,
                    title: Text("Green"),
                    onChanged: colorNavBarChanged,
                    dense: true,
                    groupValue: _navBarColor),
                RadioListTile(
                    value: Colors.white12,
                    title: Text("white"),
                    onChanged: colorNavBarChanged,
                    dense: true,
                    groupValue: _navBarColor),
                Divider(height: 25.0),
                renderTitle("Navigation Bar Style:"),
                RadioListTile(
                    value: NavigationBarStyle.DEFAULT,
                    title: Text("DEFAULT"),
                    onChanged: navigationBarStyleChanged,
                    dense: true,
                    groupValue: _navBarStyle),
                RadioListTile(
                    value: NavigationBarStyle.LIGHT,
                    title: Text("LIGHT"),
                    onChanged: navigationBarStyleChanged,
                    dense: true,
                    groupValue: _navBarStyle),
                RadioListTile(
                    value: NavigationBarStyle.DARK,
                    title: Text("DARK"),
                    onChanged: navigationBarStyleChanged,
                    dense: true,
                    groupValue: _navBarStyle),
                Divider(height: 25.0),
                renderTitle("Fullscreen mode:"),
                SwitchListTile(
                  title: new Text("Fullscreen:"),
                  value: _fullscreenMode,
                  onChanged: (bool val) {
                    this.setState(() {
                      _fullscreenMode = val;
                    });
                    FlutterStatusbarManager.setFullscreen(_fullscreenMode);
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}