如果用户的默认主题在 flutter 上是暗的,如何获取 bool 值(true)?

How to get a bool value (true) if the user's default theme is dark on flutter?

当默认主题配置为深色时,我正在尝试在代码中手动更改颜色。

有谁知道当用户的默认系统主题在 flutter 上为暗时,我如何获得布尔值 (true)?

我花了很多时间在google和pub.dev中搜索,但我没有发现类似的问题。

这是一个例子

backgroundColor: _isthemedark ? Colors.blue : Colors.red

这是我的代码完整代码

import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:flutter/services.dart';




void main() {

  SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(statusBarColor: Colors.transparent));///status bar transparent
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {


  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  bool _isObscure = true;

  final bool _isthemedark = true;/// HERE IS WHERE I WANT TO CHANGE

  @override
  Widget build(BuildContext context) {


    return MaterialApp(

     /// color: HexColor("#fafafa"),
      themeMode: ThemeMode.system,
      darkTheme: ThemeData.dark(),
      home: Scaffold(
        backgroundColor: _isthemedark ? HexColor("#2b2e4a") : HexColor("#fafafa"),
        body: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              children: [
                Row(
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(top: 150, left: 20),
                      child: Text('Opa!',
                          style:
                              TextStyle(fontWeight: FontWeight.bold,
                                  fontSize: 30,
                                  color: _isthemedark ? Colors.white : HexColor("#2b2e4a") ,),),
                    ),
                  ],
                ),///texto

                const SizedBox(
                  height: 100,
                  width: 20,
                ),///blankspace

                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 30),
                  child: TextField(
                    cursorColor: _isthemedark ? Colors.white : Colors.black,
                    decoration: InputDecoration(
                        focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                                color: _isthemedark? Colors.white : HexColor("#666a7b").withOpacity(0.7))),
                        labelText: 'Username',
                        labelStyle: TextStyle(color: HexColor("#666a7b")),
                        floatingLabelBehavior: FloatingLabelBehavior.always),
                  ),
                ),///Username field

                const SizedBox(
                  height: 70,
                ),///blankspace

                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 30),
                  child: TextField(
                    obscureText: _isObscure,
                    cursorColor: _isthemedark ? Colors.white : Colors.black,
                    decoration: InputDecoration(
                        suffixIcon: IconButton(
                          color: HexColor("#05c46b"),
                          icon: Icon(_isObscure
                              ? Icons.visibility_off
                              : Icons.visibility,
                              color: _isObscure ? HexColor("#fafafa"):HexColor("#05c46b")),
                          onPressed: () {
                            setState(() {
                              _isObscure = !_isObscure;
                            });
                          },
                        ),
                        focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                                color: _isthemedark ? Colors.white : HexColor("#666a7b").withOpacity(0.7))),
                        labelText: 'Password',
                        labelStyle: TextStyle(color: HexColor("#666a7b")),
                        floatingLabelBehavior: FloatingLabelBehavior.always),
                  ),
                ),///password field

                const SizedBox(
                  height: 20,
                ),///blank space

                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 20),
                      child: TextButton(
                          style:TextButton.styleFrom(
                              alignment: Alignment.topRight,
                              primary: HexColor("#666a7b")
                          ),
                          onPressed: () {}, child: const Text('Opa senha?')),
                    ),
                  ],
                ),///tanso?

                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 30),
                  child: SizedBox(
                    width: 450,
                    child: TextButton(
                      child: const Text ('LOGIN'),
                      onPressed: () {},
                      style: TextButton.styleFrom(
                        shadowColor: HexColor("#05c46b"),
                        elevation: 20,
                        primary: Colors.white,
                        backgroundColor: HexColor("#05c46b"),
                      ),
                    ),
                  ),
                ),///LOGIN button

                const SizedBox(
                  height: 30,
                ),///blank space

                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  child: TextButton(
                      style:TextButton.styleFrom(
                          alignment: Alignment.topRight,
                          primary: HexColor("#666a7b")
                      ),
                      onPressed: () {}, child: const Text('Criar Conta')),
                )///criar acc

              ],
            ),
          ),
        ),
      ),
    );
  }
}///Login page

更新代码:

import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:flutter/services.dart';

void main() {
  SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(statusBarColor: Colors.transparent));

  ///status bar transparent
  runApp(const LoginPage());
}
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: LoginPage(),
    );
  }
}

class LoginPage extends StatefulWidget {
  const LoginPage ({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> with WidgetsBindingObserver {

  late String theme;
  var brightness = WidgetsBinding.instance?.window.platformBrightness;
  bool _isObscure = true;
  late bool _isThemeDark;


  @override
  void initState() {
    WidgetsBinding.instance?.addObserver(this);
    if (brightness == Brightness.dark) {
      theme = Brightness.dark.toString();
      _isThemeDark = true;
    } else {
      theme = Brightness.light.toString();
      _isThemeDark = false;
    }
    super.initState();
  }

  @override
  void dispose() {
    WidgetsBinding.instance?.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangePlatformBrightness() {
    if (brightness == Brightness.dark) {
      theme = Brightness.dark.toString();
      _isThemeDark = true;
    } else {
      theme = Brightness.light.toString();
      _isThemeDark = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    ///############## If I put the code above, it crashes (Red Screen)
    ///final dark = MediaQuery.of(context).platformBrightness == Brightness.dark;
    ///##############
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      /// color: HexColor("#fafafa"),
      themeMode: ThemeMode.system,
      darkTheme: ThemeData.dark(),
      home: Scaffold(
        backgroundColor: _isThemeDark ? HexColor("#2b2e4a") : HexColor("#fafafa"),
        body: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              children: [
                Row(
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(top: 150, left: 20),
                      child: Text(
                        'Opa!',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 30,
                          color:
                          _isThemeDark ? Colors.white : HexColor("#2b2e4a"),
                        ),
                      ),
                    ),
                  ],
                ),///texto


                const SizedBox(
                  height: 100,
                  width: 20,
                ),


                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 30),
                  child: TextField(
                    cursorColor: _isThemeDark ? Colors.white : Colors.black,
                    decoration: InputDecoration(
                        focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                                color: _isThemeDark
                                    ? Colors.white
                                    : Colors.black)),
                        labelText: 'Username',
                        labelStyle: TextStyle(color: HexColor("#666a7b")),
                        floatingLabelBehavior: FloatingLabelBehavior.always),
                  ),
                ),///Username field


                const SizedBox(
                  height: 70,
                ),///blankspace


                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 30),
                  child: TextField(
                    obscureText: _isObscure,
                    cursorColor: _isThemeDark ? Colors.white : Colors.black,
                    decoration: InputDecoration(
                        suffixIcon: IconButton(
                          color: HexColor("#05c46b"),
                          icon: Icon(
                              _isObscure
                                  ? Icons.visibility_off
                                  : Icons.visibility,
                              color: _isObscure
                                  ? HexColor("#fafafa")
                                  : HexColor("#05c46b")),
                          onPressed: () {
                            setState(() {
                              _isObscure = !_isObscure;
                            });
                          },
                        ),
                        focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                                color: _isThemeDark
                                    ? Colors.white
                                    : Colors.black)),
                        labelText: 'Password',
                        labelStyle: TextStyle(color: HexColor("#666a7b")),
                        floatingLabelBehavior: FloatingLabelBehavior.always),
                  ),
                ),///password field


                const SizedBox(
                  height: 20,
                ),///blank space


                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 20),
                      child: TextButton(
                          style: TextButton.styleFrom(
                              alignment: Alignment.topRight,
                              primary: HexColor("#666a7b")),
                          onPressed: () {},
                          child: const Text('Opa senha?')),
                    ),
                  ],
                ),///tanso?


                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 30),
                  child: SizedBox(
                    width: 450,
                    child: TextButton(
                      child: const Text('LOGIN'),
                      onPressed: () {},
                      style: TextButton.styleFrom(
                        shadowColor: HexColor("#05c46b"),
                        elevation: 20,
                        primary: Colors.white,
                        backgroundColor: HexColor("#05c46b"),
                      ),
                    ),
                  ),
                ),///LOGIN button


                const SizedBox(
                  height: 30,
                ),///blank space


                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  child: TextButton(
                      style: TextButton.styleFrom(
                          alignment: Alignment.topRight,
                          primary: HexColor("#666a7b")),
                      onPressed: () {},
                      child: const Text('Criar Conta')),
                )///criar acc


              ],
            ),
          ),
        ),
      ),
    );
  }
}

使用MediaQuery插件查看平台亮度是否暗:

final dark = MediaQuery.of(context).platformBrightness == Brightness.dark;

将上面的代码放在build方法中,这样当用户更改系统设置时,您的应用程序将自动重建。


完整示例,根据默认的 flutter counter 项目修改,仅更改 2 行:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    /// @@@@@@@@@@@@@@@@@@@ New line below:
    final dark = MediaQuery.of(context).platformBrightness == Brightness.dark;
    /// @@@@@@@@@@@@@@@@@@@ New line above.

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),

            /// @@@@@@@@@@@@@@@@@@@ New line below:
            Text(dark ? 'Dark Mode' : 'Light Mode'),
            /// @@@@@@@@@@@@@@@@@@@ New line above.
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

在您的代码中添加一行:

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

void main() {
  SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(statusBarColor: Colors.transparent));

  ///status bar transparent
  runApp(const LoginPage());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: LoginPage(),
    );
  }
}

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> with WidgetsBindingObserver {
  late String theme;
  var brightness = WidgetsBinding.instance?.window.platformBrightness;
  bool _isObscure = true;
  late bool _isThemeDark;

  @override
  void initState() {
    WidgetsBinding.instance?.addObserver(this);
    if (brightness == Brightness.dark) {
      theme = Brightness.dark.toString();
      _isThemeDark = true;
    } else {
      theme = Brightness.light.toString();
      _isThemeDark = false;
    }
    super.initState();
  }

  @override
  void dispose() {
    WidgetsBinding.instance?.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangePlatformBrightness() {
    if (brightness == Brightness.dark) {
      theme = Brightness.dark.toString();
      _isThemeDark = true;
    } else {
      theme = Brightness.light.toString();
      _isThemeDark = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    ///#####################################################################
    final dark = MediaQuery.of(context).platformBrightness == Brightness.dark;
    ///#####################################################################
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      themeMode: ThemeMode.system,
      darkTheme: ThemeData.dark(),
      home: Scaffold(
        appBar: AppBar(title: const Text('Login Page')),
        body: Center(
          child: Text('dark: $dark'),
        ),
      ),
    );
  }
}

使用

收听变化
void didChangePlatformBrightness()

https://docs-flutter-io.firebaseapp.com/flutter/widgets/WidgetsBindingObserver/didChangePlatformBrightness.html

import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:flutter/services.dart';

void main() {
  SystemChrome.setSystemUIOverlayStyle(
      const SystemUiOverlayStyle(statusBarColor: Colors.transparent));

  ///status bar transparent
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  
  late String theme;
  var brightness = WidgetsBinding.instance?.window.platformBrightness;
  bool _isObscure = true;
  late bool _isThemeDark;

  /// HERE IS WHERE I WANT TO CHANGE

  @override
  void initState() {
    WidgetsBinding.instance?.addObserver(this);
    if (brightness == Brightness.dark) {
      theme = Brightness.dark.toString();
      _isThemeDark = true;
    } else {
      theme = Brightness.light.toString();
      _isThemeDark = false;
    }
    super.initState();
  }

  @override
  void dispose() {
    WidgetsBinding.instance?.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangePlatformBrightness() {
    if (brightness == Brightness.dark) {
      theme = Brightness.dark.toString();
      _isThemeDark = true;
    } else {
      theme = Brightness.light.toString();
      _isThemeDark = false;
    }
  }

  @override
  Widget build(BuildContext context) {
    print("CHECK CONSOLE");
    print(theme);
    print(_isThemeDark);
    return MaterialApp(
      /// color: HexColor("#fafafa"),
      themeMode: ThemeMode.system,
      darkTheme: ThemeData.dark(),
      home: Scaffold(
        backgroundColor: _isThemeDark ? HexColor("#2b2e4a") : HexColor("#fafafa"),
        body: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              children: [
                Row(
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(top: 150, left: 20),
                      child: Text(
                        'Opa!',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 30,
                          color:
                              _isThemeDark ? Colors.white : HexColor("#2b2e4a"),
                        ),
                      ),
                    ),
                  ],
                ),

                ///texto
                const SizedBox(
                  height: 100,
                  width: 20,
                ),

                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 30),
                  child: TextField(
                    cursorColor: _isThemeDark ? Colors.white : Colors.black,
                    decoration: InputDecoration(
                        focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                                color: _isThemeDark
                                    ? Colors.white
                                    : HexColor("#666a7b").withOpacity(0.7))),
                        labelText: 'Username',
                        labelStyle: TextStyle(color: HexColor("#666a7b")),
                        floatingLabelBehavior: FloatingLabelBehavior.always),
                  ),
                ),

                ///Username field

                const SizedBox(
                  height: 70,
                ),

                ///blankspace

                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 30),
                  child: TextField(
                    obscureText: _isObscure,
                    cursorColor: _isThemeDark ? Colors.white : Colors.black,
                    decoration: InputDecoration(
                        suffixIcon: IconButton(
                          color: HexColor("#05c46b"),
                          icon: Icon(
                              _isObscure
                                  ? Icons.visibility_off
                                  : Icons.visibility,
                              color: _isObscure
                                  ? HexColor("#fafafa")
                                  : HexColor("#05c46b")),
                          onPressed: () {
                            setState(() {
                              _isObscure = !_isObscure;
                            });
                          },
                        ),
                        focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                                color: _isThemeDark
                                    ? Colors.white
                                    : HexColor("#666a7b").withOpacity(0.7))),
                        labelText: 'Password',
                        labelStyle: TextStyle(color: HexColor("#666a7b")),
                        floatingLabelBehavior: FloatingLabelBehavior.always),
                  ),
                ),

                ///password field

                const SizedBox(
                  height: 20,
                ),

                ///blank space

                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 20),
                      child: TextButton(
                          style: TextButton.styleFrom(
                              alignment: Alignment.topRight,
                              primary: HexColor("#666a7b")),
                          onPressed: () {},
                          child: const Text('Opa senha?')),
                    ),
                  ],
                ),

                ///tanso?

                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 30),
                  child: SizedBox(
                    width: 450,
                    child: TextButton(
                      child: const Text('LOGIN'),
                      onPressed: () {},
                      style: TextButton.styleFrom(
                        shadowColor: HexColor("#05c46b"),
                        elevation: 20,
                        primary: Colors.white,
                        backgroundColor: HexColor("#05c46b"),
                      ),
                    ),
                  ),
                ),

                ///LOGIN button

                const SizedBox(
                  height: 30,
                ),

                ///blank space

                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  child: TextButton(
                      style: TextButton.styleFrom(
                          alignment: Alignment.topRight,
                          primary: HexColor("#666a7b")),
                      onPressed: () {},
                      child: const Text('Criar Conta')),
                )

                ///criar acc
              ],
            ),
          ),
        ),
      ),
    );
  }
}