我的目标是在用户向下滚动时更改应用栏的颜色和不透明度。
我的逻辑是:
- 滚动偏移量 = 0:appbar 为红色,不透明度 = 1
- 0 < 滚动偏移 < 40 : appbar 为蓝色,不透明度 = 0.4
- 40 <= 滚动偏移:appbar 为蓝色,不透明度与滚动偏移成正比
我想出了以下代码:
import 'package:flutter/material.dart';
import 'package:gradient_app_bar/gradient_app_bar.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var _gradientColor1 = Colors.red[400];
var _gradientColor2 = Colors.red[800];
ScrollController _scrollViewController;
void changeColor(){
if((_scrollViewController.offset == 0) && (_gradientColor1 != Colors.red[400])){
setState(() {
_gradientColor1 = Colors.red[400];
_gradientColor2 = Colors.red[800];
});
}else if((_scrollViewController.offset <= 40) && (_gradientColor1 != Color.fromRGBO(66,165,245 ,0.4))){
setState(() {
_gradientColor1 = Color.fromRGBO(66,165,245 ,0.4);
_gradientColor2 = Color.fromRGBO(21,101,192 ,0.4);
});
}else if((_scrollViewController.offset <= 100) && (_scrollViewController.offset > 40)){
var opacity = _scrollViewController.offset/100;
setState(() {
_gradientColor1 = Color.fromRGBO(66,165,245 ,opacity);
_gradientColor2 = Color.fromRGBO(21,101,192 ,opacity);
});
}
}
@override
void initState() {
_scrollViewController = ScrollController(initialScrollOffset: 0.0);
_scrollViewController.addListener(changeColor);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: GradientAppBar(
backgroundColorStart: _gradientColor1,
backgroundColorEnd: _gradientColor2,
elevation: 0,
),
body: SingleChildScrollView(
controller: _scrollViewController,
child: Column(
children: <Widget>[
Container(color: Colors.red, height: 400,),
Container(color: Colors.purple, height: 400,),
],
),
),
);
}
}
它按预期工作,但随着用户界面的复杂化而变得滞后。在我的示例中,我使用的是 GradientAppbar:https ://github.com/joostlek/GradientAppBar