首页 > 解决方案 > 根据暗/亮模式将彩色背景替换为颤动应用程序的渐变背景

问题描述

我想将我的颤振应用程序的标准主题背景颜色更改为渐变背景,具体取决于暗/亮模式。使亮模式显示与暗模式不同的渐变。我设法用容器和装饰来做到这一点,它被分解成单独的页面,有时结果令人满意,有时结果不太令人满意,因为这仅涵盖背景,因此应用程序不再完全顺利运行。所以我认为正确的方法必须是通过活泼的普通背景来整合它,但不幸的是我完全不知道这是否可能......

这是我的 main.dart 的摘录

  @override
  Widget build(BuildContext context) {
    bool isDark = Theme.of(context).brightness == Brightness.dark;
    return Padding(
      child: MaterialApp(
        locale: _getLocale(),
        navigatorKey: Magazin.navKey,
        title: Config.appTitle,
        theme: ThemeData(
          primarySwatch: Colors.blue,
          brightness: _brightness,
          canvasColor: _brightness == Brightness.dark
              ? Color(0xFF282C39)
              : Color(0xFF565A67),
          primaryColor: _brightness == Brightness.dark
              ? Color(0xFF1B1E28)
              : Color(0xFF34445c),
        ),

我以为我可以从这段代码中修改它,但我认为我不太正确,我希望我已经提到了所有重要的事情。我也不确定是否有适合新手代码的简单解决方案,....感谢您阅读本文:-)

              decoration: BoxDecoration(
                  gradient: LinearGradient(
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                      stops: [0.2, 0.5, 0.7, 1],
                      colors: [Colors.black12, Colors.grey, Colors.black54, Colors.black45])
              ),

标签: flutterbackgroundgradient

解决方案


也许你可以将你的Scaffold内部嵌入一个Container定义渐变?

在此处输入图像描述

记得定义backgroundColor你的Scaffoldas Colors.transparent

完整源代码:

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      home: HomePage(),
    ),
  );
}

class AppLayout extends StatelessWidget {
  final Widget child;

  const AppLayout({Key key, this.child}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          stops: [0.2, 0.5, 0.7, 1],
          colors: [Colors.black12, Colors.grey, Colors.black54, Colors.black45],
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: child,
      ),
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return AppLayout(
      child: Center(
        child: Text(
          'Hello, GHOST!',
          style: TextStyle(
            fontSize: 48,
            color: Colors.white70,
          ),
        ),
      ),
    );
  }
}

推荐阅读