我想根据我的手机系统动态改变我的应用程序的主题颜色。比如,如果我把手机设为暗模式,我的应用程序就会变暗,如果我把它设为亮模式,它就会变亮。我一直在互联网上,但我所看到的都是人们使用一个按钮。如果有办法,也许是通过依赖,我很想知道。我还想看看是否可以动态地改变支架的颜色。我的代码
main.dart
import 'package:figma_test/home/home.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setSystemUIOverlayStyle(
const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarBrightness: Brightness.dark
));
runApp(
const MyApp()
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
final lightTheme = ThemeData(
brightness: Brightness.light,
primarySwatch: Colors.blue,
fontFamily: 'Roboto',
);
final darkTheme = ThemeData(
brightness: Brightness.dark,
primarySwatch: Colors.blueGrey,
fontFamily: 'Roboto',
);
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
useMaterial3: true,
),
home: Home(),
);
}
}
home.dart
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class Home extends StatelessWidget {
Home({Key? key}) : super(key: key);
final List<String> _images = [
'img1.jpeg',
'img2.jpeg',
'img3.jpeg',
'img4.jpeg',
'img5.jpeg'
];
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xfffafafa),
appBar: PreferredSize(
preferredSize: Size.fromHeight(30),
child: AppBar(
backgroundColor: Colors.white,
),
),
body: SingleChildScrollView(
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 15),
child: Row(
children: [
const Icon(Icons.close),
const SizedBox(
width: 13,
),
Text('Product Name',
style: GoogleFonts.roboto(
fontWeight: FontWeight.w400,
fontSize: 22
),
)
],
),
),
const SizedBox(
height: 20,
),
SizedBox(
height: 400,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: _images.length,
itemBuilder: (context, index){
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 400,
width: MediaQuery.of(context).size.width*0.9,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('asset/images/${_images[index]}',),
fit: BoxFit.fill
),
boxShadow: [
BoxShadow(
color: Colors.grey.shade400,
blurRadius: 2,
spreadRadius: 2,
offset: const Offset(
1.0,
2.0
)
)
],
borderRadius: BorderRadius.circular(20),
color: Color(0xffe7edf9)
),
),
);
}
),
)
],
),
),
);
}
}
我不太确定您的意思,但是您可以根据用户的系统主题轻松更改主题。
在MaterialApp()
中,可以将themeMode
属性设置为:
ThemeMode.dark
ThemeMode.light
ThemeMode.system
下面是我在代码中的使用方法:
return MaterialApp(
darkTheme: ThemeData(brightness: Brightness.dark),
theme: ThemeData(brightness: Brightness.light),
themeMode: ThemeMode.system,
- 如果用户的系统主题是黑色的,应用程序将使用
darkTheme:
主题。 - 如果用户的系统主题是light,应用程序将使用
theme:
主题。