Flutter入门引导页如何修改背景颜色并添加自定义字体?
实现方案
一、先修复现有代码的小问题
你代码里定义的文本数组是带下划线的私有常量_titles,后续调用时直接写了titles,会报未定义错误,修改时记得统一命名即可。
二、添加自定义字体步骤
- 第一步:在项目根目录新建
fonts文件夹,把你下载好的.ttf/.otf格式字体文件放入文件夹 - 第二步:打开项目根目录的
pubspec.yaml文件,找到flutter配置块,添加字体声明:
flutter: fonts: - family: MyCustomFont # 自定义字体名称,后续调用要和这个名字保持一致 fonts: - asset: fonts/你下载的字体文件名.ttf # 如有粗体、斜体需求,可额外添加对应权重配置 # weight: 700
- 第三步:执行
pub get加载资源,之后就可以在TextStyle中调用该字体。
三、添加彩色背景的实现
你可以按需选择两种实现方案:
- 固定彩色背景:直接用
Container加decoration属性设置纯色/渐变,套在Stack外层即可 - 随文本切换动态变色背景:可给背景绑定index参数,每切换一句文本就对应更换背景样式
四、修改后的完整代码
import 'dart:async'; import 'package:flutter/material.dart'; class IntroScreen extends StatefulWidget { @override _IntroScreenState createState() => _IntroScreenState(); } class _IntroScreenState extends State<IntroScreen> { static const _titles = <String>[ "疫情让我们感到\n不安", "专注于对你而言\n真正重要的事", "创建待办任务\n完成后戳破泡泡", ]; // 可选配置:对应每个文本的渐变背景,不需要动态切换的话直接写死一个渐变即可 static const _backgroundGradients = <Gradient>[ LinearGradient( colors: [Color(0xFF6DD5FA), Color(0xFF2980B9)], begin: Alignment.topLeft, end: Alignment.bottomRight, ), LinearGradient( colors: [Color(0xFFFFF176), Color(0xFFFF4081)], begin: Alignment.topLeft, end: Alignment.bottomRight, ), LinearGradient( colors: [Color(0xFFA8E063), Color(0xFF56AB2F)], begin: Alignment.topLeft, end: Alignment.bottomRight, ), ]; Timer? timer; int index = 0; @override void initState() { super.initState(); timer = Timer.periodic(const Duration(seconds: 3), (timer) { if (index < _titles.length - 1) { setState(() { index++; }); } if (index == _titles.length - 1) { timer.cancel(); print("引导页轮播完成"); } }); } @override Widget build(BuildContext context) { return Material( // 背景实现部分 child: Container( decoration: BoxDecoration( // 不需要动态背景的话直接写死gradient参数即可,不需要绑定index gradient: _backgroundGradients[index], ), child: Stack(children: [ Center( child: AnimatedSwitcher( duration: const Duration(milliseconds: 1000), child: Text( _titles[index], key: ValueKey(_titles[index]), textAlign: TextAlign.center, style: Theme.of(context).textTheme.headline4?.copyWith( // 调用自定义字体,名称和pubspec里的family参数保持一致 fontFamily: 'MyCustomFont', // 可自行调整字体颜色、字号适配背景 color: Colors.white, ), ), ), ), Positioned( bottom: 34, right: 34, child: TextButton( onPressed: () {}, child: Text( "跳过", style: Theme.of(context).textTheme.headline6?.copyWith( fontFamily: 'MyCustomFont', color: Colors.white70, ), ), ), ) ]), ), ); } @override void dispose() { timer?.cancel(); super.dispose(); } }
其他可选调整
- 如果觉得渐变太花哨,也可以直接把
gradient换成color参数设置纯色背景,或者添加半透明遮罩、背景图片,直接修改Container的decoration配置即可。 - 如果想要背景切换也有平滑过渡效果,把外层的Container换成
AnimatedContainer,设置和文本动画一致的duration参数,切换文本时背景会自动生成过渡动画。
内容的提问来源于stack exchange,提问作者Sultan ul Arefin
相关产品推荐
相关产品推荐

