diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..aba38de --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,11 @@ +include: package:flutter_lints/flutter.yaml + +analyzer: + errors: + mixin_inherits_from_not_object: ignore + +linter: + rules: + library_private_types_in_public_api: false + constant_identifier_names: false + library_prefixes: false \ No newline at end of file diff --git a/lib/main.dart b/lib/main.dart index 4062e04..0a46fcd 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,3 +1,4 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:gsy_flutter_demo/widget/align_demo_page.dart' deferred as align_demo_page; @@ -213,9 +214,11 @@ import 'package:gsy_flutter_demo/widget/pageview_in_pageview_demo_page.dart' import 'package:window_location_href/window_location_href.dart'; -void main() => runApp(MyApp()); +void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { + const MyApp({super.key}); + // This widget is the root of your application. @override Widget build(BuildContext context) { @@ -224,34 +227,36 @@ class MyApp extends StatelessWidget { theme: ThemeData( useMaterial3: false, primarySwatch: Colors.blue, - textButtonTheme: TextButtonThemeData( + textButtonTheme: const TextButtonThemeData( // 去掉 TextButton 的水波纹效果 style: ButtonStyle(splashFactory: NoSplash.splashFactory), ), ), - home: MyHomePage(title: 'GSY Flutter Demo'), + home: const MyHomePage(title: 'GSY Flutter Demo'), routes: routers, ); } } class MyHomePage extends StatefulWidget { - MyHomePage({Key? key, this.title}) : super(key: key); + const MyHomePage({super.key, this.title}); final String? title; @override - _MyHomePageState createState() => _MyHomePageState(); + MyHomePageState createState() => MyHomePageState(); } -class _MyHomePageState extends State { +class MyHomePageState extends State { @override void initState() { //loadLibrary(); super.initState(); - print("get enum value with 2.15 ${Cat.white.name}"); - print("get enum value with 2.15 ${Cat.values.byName("black")}"); - print("get enum value with 2.17 ${Cat.white.value} ${Cat.white}"); + if (kDebugMode) { + print("get enum value with 2.15 ${Cat.white.name}"); + print("get enum value with 2.15 ${Cat.values.byName("black")}"); + print("get enum value with 2.17 ${Cat.white.value} ${Cat.white}"); + } final href = getHref(); int? index = href?.indexOf("#"); @@ -276,25 +281,23 @@ class _MyHomePageState extends State { appBar: AppBar( title: Text(widget.title!), ), - body: new Container( - child: new ListView.builder( - itemBuilder: (context, index) { - return new InkWell( - onTap: () { - Navigator.of(context).pushNamed(routeLists[index]); - }, - child: new Card( - child: new Container( - alignment: Alignment.centerLeft, - margin: EdgeInsets.symmetric(horizontal: 10), - height: 50, - child: new Text(routers.keys.toList()[index]), - ), + body: ListView.builder( + itemBuilder: (context, index) { + return InkWell( + onTap: () { + Navigator.of(context).pushNamed(routeLists[index]); + }, + child: Card( + child: Container( + alignment: Alignment.centerLeft, + margin: const EdgeInsets.symmetric(horizontal: 10), + height: 50, + child: Text(routers.keys.toList()[index]), ), - ); - }, - itemCount: routers.length, - ), + ), + ); + }, + itemCount: routers.length, ), // This trailing comma makes auto-formatting nicer for build methods. ); } @@ -307,7 +310,7 @@ class ContainerAsyncRouterPage extends StatelessWidget { ///稍后更新文章到掘金 final WidgetBuilder child; - ContainerAsyncRouterPage(this.libraryFuture, this.child); + const ContainerAsyncRouterPage(this.libraryFuture, this.child, {super.key}); @override Widget build(BuildContext context) { @@ -322,7 +325,7 @@ class ContainerAsyncRouterPage extends StatelessWidget { alignment: Alignment.center, child: Text( 'Error: ${s.error}', - style: TextStyle(color: Colors.red), + style: const TextStyle(color: Colors.red), ), ), ); @@ -333,7 +336,7 @@ class ContainerAsyncRouterPage extends StatelessWidget { appBar: AppBar(), body: Container( alignment: Alignment.center, - child: CircularProgressIndicator(), + child: const CircularProgressIndicator(), ), ); }); @@ -940,6 +943,8 @@ extension CatExtension on Cat { // } void talk() { - print('meow'); + if (kDebugMode) { + print('meow'); + } } } diff --git a/lib/widget/align_demo_page.dart b/lib/widget/align_demo_page.dart index 1f5b747..81369b2 100644 --- a/lib/widget/align_demo_page.dart +++ b/lib/widget/align_demo_page.dart @@ -2,22 +2,24 @@ import 'dart:math' as math; import 'package:flutter/material.dart'; class AlignDemoPage extends StatefulWidget { + const AlignDemoPage({super.key}); + @override - _AlignDemoPageState createState() => _AlignDemoPageState(); + AlignDemoPageState createState() => AlignDemoPageState(); } -class _AlignDemoPageState extends State +class AlignDemoPageState extends State with SingleTickerProviderStateMixin { getAlign(x) { return Align( - child: new Container( + alignment: Alignment(math.cos(x * math.pi), math.sin(x * math.pi)), + child: Container( height: 20, width: 20, - decoration: BoxDecoration( + decoration: const BoxDecoration( color: Colors.green, borderRadius: BorderRadius.all(Radius.circular(10))), ), - alignment: Alignment(math.cos(x * math.pi), math.sin(x * math.pi)), ); } @@ -26,11 +28,11 @@ class _AlignDemoPageState extends State int size = 20; return Scaffold( appBar: AppBar( - title: new Text("AlignDemoPage"), + title: const Text("AlignDemoPage"), ), - body: new Container( - alignment: Alignment(0, 0), - child: Container( + body: Container( + alignment: const Alignment(0, 0), + child: SizedBox( height: MediaQuery.sizeOf(context).width, width: MediaQuery.sizeOf(context).width, child: Stack( diff --git a/lib/widget/anim_bg_demo_page.dart b/lib/widget/anim_bg_demo_page.dart index d56acc5..9846719 100644 --- a/lib/widget/anim_bg_demo_page.dart +++ b/lib/widget/anim_bg_demo_page.dart @@ -6,34 +6,36 @@ import 'package:supercharged/supercharged.dart'; enum _ColorTween { color1, color2 } class AnimBgDemoPage extends StatelessWidget { + const AnimBgDemoPage({super.key}); + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("AnimBgDemoPage"), + title: const Text("AnimBgDemoPage"), ), body: Stack( children: [ - Positioned.fill(child: AnimatedBackground()), - onBottom(AnimatedWave( + const Positioned.fill(child: AnimatedBackground()), + onBottom(const AnimatedWave( height: 180, speed: 1.0, )), - onBottom(AnimatedWave( + onBottom(const AnimatedWave( height: 120, speed: 0.9, offset: pi, )), - onBottom(AnimatedWave( + onBottom(const AnimatedWave( height: 220, speed: 1.2, offset: pi / 2, )), - Positioned.fill( - child: new Center( - child: new Text( + const Positioned.fill( + child: Center( + child: Text( "GSY Flutter Demo", - style: new TextStyle( + style: TextStyle( fontSize: 30, fontWeight: FontWeight.bold, color: Colors.white), @@ -57,12 +59,12 @@ class AnimatedWave extends StatelessWidget { final double? speed; final double offset; - AnimatedWave({this.height, this.speed, this.offset = 0.0}); + const AnimatedWave({super.key, this.height, this.speed, this.offset = 0.0}); @override Widget build(BuildContext context) { return LayoutBuilder(builder: (context, constraints) { - return Container( + return SizedBox( height: height, width: constraints.biggest.width, child: LoopAnimationBuilder( @@ -112,17 +114,19 @@ class CurvePainter extends CustomPainter { } class AnimatedBackground extends StatelessWidget { + const AnimatedBackground({super.key}); + @override Widget build(BuildContext context) { final tween = MovieTween() ..tween( _ColorTween.color1, - Color(0xffD38312).tweenTo(Colors.lightBlue.shade900), + const Color(0xffD38312).tweenTo(Colors.lightBlue.shade900), duration: 3.seconds, ) ..tween( _ColorTween.color2, - Color(0xffA83279).tweenTo(Colors.blue.shade600), + const Color(0xffA83279).tweenTo(Colors.blue.shade600), duration: 3.seconds, ); diff --git a/lib/widget/anim_bubble_gum.dart b/lib/widget/anim_bubble_gum.dart index e1c6995..25d9dd0 100644 --- a/lib/widget/anim_bubble_gum.dart +++ b/lib/widget/anim_bubble_gum.dart @@ -9,13 +9,15 @@ import 'package:flutter/material.dart'; /// https://codepen.io/rx-labz/pen/xxwdGaM?__cf_chl_jschl_tk__=830b2fd03dd1ccb9ac8d7c1fdbdee39e71fc2e7c-1587971334-0-AQ6h_JKRflUPLJcJhlH7eT841oCDgD5EttuC0cq9I50PQHwBtecDMdA9H-_a9FitSk4HQwlPO3dvvYn83act0FI6ufSlRL7MCB-gJVkKQov2i-AVA92X3KFwD93JOfog1LMy9yTdUyNb1zr43ZgC2X-cg0IsMGPr6U54kAb40AQgoK-KbYc9-KYWUIFqFy8pShOZIfn23-0lInSjKlJ3p8rnLXp84p7rhdTNrQU0pWPKNiDkuuthEaqzi9THfk4-iTrZ3CJ6wU0t81T9GyKwIT5VthFlnuPyNqIKseggtyxBxgZJ4W4ec6FmQoFp7bYAQF9rFb3D5L_3juEL-262JH_TP20ojcgjb30pvNnHyTfh class AnimBubbleGumDemoPage extends StatelessWidget { + const AnimBubbleGumDemoPage({super.key}); + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("AnimBubbleGumDemoPage"), + title: const Text("AnimBubbleGumDemoPage"), ), - body: Container(color: Colors.pink[200], child: AnimBubbleGum()), + body: Container(color: Colors.pink[200], child: const AnimBubbleGum()), ); } } @@ -40,18 +42,20 @@ class Circle { } class AnimBubbleGum extends StatefulWidget { + const AnimBubbleGum({super.key}); + @override - _AnimBubbleGumState createState() => _AnimBubbleGumState(); + AnimBubbleGumState createState() => AnimBubbleGumState(); } -class _AnimBubbleGumState extends State { +class AnimBubbleGumState extends State { late Timer timer; final circles = []; late Size size; - Offset force = Offset(1, 1); + Offset force = const Offset(1, 1); HSLColor hslColor = HSLColor.fromColor(Colors.pink[100]!); @@ -70,7 +74,7 @@ class _AnimBubbleGumState extends State { timer = Timer.periodic( frequency, (t) { - if (circles.isEmpty) + if (circles.isEmpty) { _circleStreamer.add( circles ..add( @@ -81,6 +85,7 @@ class _AnimBubbleGumState extends State { ), ), ); + } int count = 0; while (count < 29) { final p = // newPoint @@ -118,7 +123,7 @@ class _AnimBubbleGumState extends State { Widget build(BuildContext context) => Stack( children: [ StreamBuilder>( - initialData: [], + initialData: const [], stream: _circle$.map( (event) => event.length > numCircles ? event @@ -164,11 +169,12 @@ class Painter extends CustomPainter { c.offset! - Offset(0, c.radius), c.radius, [ - Color(0x53ffffff), + const Color(0x53ffffff), Colors.transparent, ], ); } + // ignore: empty_catches } catch (e) {} //too heavy for mobile web rendering diff --git a/lib/widget/anim_button/anim_button_demo_page.dart b/lib/widget/anim_button/anim_button_demo_page.dart index c0e0d5d..485a2a1 100644 --- a/lib/widget/anim_button/anim_button_demo_page.dart +++ b/lib/widget/anim_button/anim_button_demo_page.dart @@ -6,11 +6,13 @@ import 'package:gsy_flutter_demo/widget/anim_button/play_anim_button.dart'; import 'loading_anim_button.dart'; class AnimButtonDemoPage extends StatefulWidget { + const AnimButtonDemoPage({super.key}); + @override - _AnimButtonDemoPageState createState() => _AnimButtonDemoPageState(); + AnimButtonDemoPageState createState() => AnimButtonDemoPageState(); } -class _AnimButtonDemoPageState extends State { +class AnimButtonDemoPageState extends State { LoadingState? loadingState = LoadingState.STATE_PRE; updateState() { @@ -19,33 +21,29 @@ class _AnimButtonDemoPageState extends State { @override Widget build(BuildContext context) { - var playButton; + Widget playButton; try { if (Platform.isAndroid == true || Platform.isIOS == true) { - playButton = SizedBox( + playButton = const SizedBox( height: 50, width: 50, child: PlayAnimButton(), ); } else { - playButton = new Container( - child: new Text( - "该控件效果暂不支持 Web,已隐藏", - style: new TextStyle(color: Colors.white, fontSize: 16), - ), + playButton = const Text( + "该控件效果暂不支持 Web,已隐藏", + style: TextStyle(color: Colors.white, fontSize: 16), ); } } catch (e) { - playButton = new Container( - child: new Text( - "该效果暂不支持 Web", - style: new TextStyle(color: Colors.white, fontSize: 16), - ), + playButton = const Text( + "该效果暂不支持 Web", + style: TextStyle(color: Colors.white, fontSize: 16), ); } return Scaffold( appBar: AppBar( - title: new Text("AnimButtonDemoPage"), + title: const Text("AnimButtonDemoPage"), ), body: Container( color: Colors.blueAccent, @@ -53,17 +51,15 @@ class _AnimButtonDemoPageState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - new Container( - child: new Text( - "点击下方按键切换动画效果", - style: new TextStyle(color: Colors.white, fontSize: 16), - ), + const Text( + "点击下方按键切换动画效果", + style: TextStyle(color: Colors.white, fontSize: 16), ), - new SizedBox( + const SizedBox( height: 50, ), playButton, - new SizedBox( + const SizedBox( height: 50, ), SizedBox( @@ -71,7 +67,7 @@ class _AnimButtonDemoPageState extends State { width: 50, child: InkWell( onTap: () { - var nextState; + LoadingState nextState; switch (loadingState) { case LoadingState.STATE_PRE: nextState = LoadingState.STATE_COMPLETE; diff --git a/lib/widget/anim_button/loading_anim_button.dart b/lib/widget/anim_button/loading_anim_button.dart index bc51ae6..5ae2a49 100644 --- a/lib/widget/anim_button/loading_anim_button.dart +++ b/lib/widget/anim_button/loading_anim_button.dart @@ -7,7 +7,7 @@ class LoadingAnimButton extends StatefulWidget { final LoadingState? loadingState; final int loadingSpeed; - LoadingAnimButton({this.loadingState, this.loadingSpeed = 2}); + const LoadingAnimButton({super.key, this.loadingState, this.loadingSpeed = 2}); @override _LoadingAnimButtonState createState() => _LoadingAnimButtonState(); @@ -25,9 +25,9 @@ class _LoadingAnimButtonState extends State @override void initState() { super.initState(); - loadingButtonController = new AnimationController(vsync: this) - ..duration = Duration(milliseconds: 1000); - this.loadingAnimation = CurvedAnimation( + loadingButtonController = AnimationController(vsync: this) + ..duration = const Duration(milliseconds: 1000); + loadingAnimation = CurvedAnimation( parent: loadingButtonController, curve: Curves.decelerate, )..addListener(updateState); @@ -105,9 +105,9 @@ class LoadingButtonPainter extends CustomPainter { painter.isAntiAlias = true; } - painter = new Paint(); + painter = Paint(); init(painter); - bgPainter = new Paint(); + bgPainter = Paint(); init(bgPainter); } @@ -122,7 +122,7 @@ class LoadingButtonPainter extends CustomPainter { centerX = w / 2; centerY = h / 2; currentRippleX = centerX - baseRippleLength * 10; - rect = new Rect.fromLTRB( + rect = Rect.fromLTRB( centerX - circleRadius, centerY + 0.6 * circleRadius, centerX + circleRadius, @@ -221,8 +221,9 @@ class LoadingButtonPainter extends CustomPainter { rect, -0.5 * pi, 359.99 / 180 * pi * fraction, false, painter); path.reset(); currentRippleX += loadingSpeed; - if (currentRippleX > centerX - baseRippleLength * 6) + if (currentRippleX > centerX - baseRippleLength * 6) { currentRippleX = centerX - baseRippleLength * 10; + } currentRippleXCallback?.call(currentRippleX); path.moveTo(currentRippleX, centerY); for (int i = 0; i < 4; i++) { diff --git a/lib/widget/anim_button/play_anim_button.dart b/lib/widget/anim_button/play_anim_button.dart index e92a7cd..a4e2546 100644 --- a/lib/widget/anim_button/play_anim_button.dart +++ b/lib/widget/anim_button/play_anim_button.dart @@ -4,6 +4,8 @@ import 'dart:ui'; import 'package:flutter/material.dart'; class PlayAnimButton extends StatefulWidget { + const PlayAnimButton({super.key}); + @override _PlayAnimButtonState createState() => _PlayAnimButtonState(); } @@ -16,9 +18,9 @@ class _PlayAnimButtonState extends State @override void initState() { super.initState(); - playerButtonController = new AnimationController(vsync: this) - ..duration = Duration(milliseconds: 1000); - this.playerAnimation = CurvedAnimation( + playerButtonController = AnimationController(vsync: this) + ..duration = const Duration(milliseconds: 1000); + playerAnimation = CurvedAnimation( parent: playerButtonController, curve: Curves.bounceInOut, )..addListener(updateState); @@ -46,7 +48,7 @@ class _PlayAnimButtonState extends State } }, child: CustomPaint( - painter: new PlayButtonPainter(fraction: playerAnimation.value), + painter: PlayButtonPainter(fraction: playerAnimation.value), ), ); } @@ -83,9 +85,9 @@ class PlayButtonPainter extends CustomPainter { painter.isAntiAlias = true; } - painter = new Paint(); + painter = Paint(); init(painter); - bgPainter = new Paint(); + bgPainter = Paint(); init(bgPainter); } @@ -97,12 +99,12 @@ class PlayButtonPainter extends CustomPainter { circleRadius = width / 8; centerX = w / 2; centerY = h / 2; - rect = new Rect.fromLTRB( + rect = Rect.fromLTRB( centerX - circleRadius, centerY + 0.6 * circleRadius, centerX + circleRadius, centerY + 2.6 * circleRadius); - bgRect = new Rect.fromLTRB(centerX - width / 2, centerY - height / 2, + bgRect = Rect.fromLTRB(centerX - width / 2, centerY - height / 2, centerX + width / 2, centerY + height / 2); path.moveTo(centerX - circleRadius, centerY + 1.8 * circleRadius); path.lineTo(centerX - circleRadius, centerY - 1.8 * circleRadius); @@ -144,8 +146,9 @@ class PlayButtonPainter extends CustomPainter { Offset(centerX - circleRadius, centerY + 1.6 * circleRadius), painter); - if (fraction != 0) + if (fraction != 0) { canvas.drawArc(rect, 0, pi / 0.3 * fraction, false, painter); + } canvas.drawArc(bgRect, -105 / 180 * pi + 2 * pi * fraction, 2 * pi * (1 - fraction), false, painter); @@ -157,7 +160,7 @@ class PlayButtonPainter extends CustomPainter { var extractPath = pathMetric.extractPath(0.02 * pathLength, 0.38 * pathLength + 0.42 * pathLength / 0.3 * (fraction - 0.3), startWithMoveTo: true); - dstPath.addPath(extractPath, Offset(0, 0)); + dstPath.addPath(extractPath, const Offset(0, 0)); canvas.drawPath(dstPath, painter); canvas.drawArc(bgRect, -105 / 180 * pi + 2 * pi * fraction, @@ -169,7 +172,7 @@ class PlayButtonPainter extends CustomPainter { 0.02 * pathLength + 0.2 * pathLength / 0.2 * (fraction - 0.6), 0.8 * pathLength + 0.2 * pathLength / 0.2 * (fraction - 0.6), startWithMoveTo: true); - dstPath.addPath(extractPath, Offset(0, 0)); + dstPath.addPath(extractPath, const Offset(0, 0)); canvas.drawPath(dstPath, painter); canvas.drawArc(bgRect, -105 / 180 * pi + 2 * pi * fraction, @@ -180,7 +183,7 @@ class PlayButtonPainter extends CustomPainter { var extractPath = pathMetric.extractPath( 10 * circleRadius * (fraction - 1), pathLength, startWithMoveTo: true); - dstPath.addPath(extractPath, Offset(0, 0)); + dstPath.addPath(extractPath, const Offset(0, 0)); canvas.drawPath(dstPath, painter); } } diff --git a/lib/widget/anim_juejin_logo_demo_page.dart b/lib/widget/anim_juejin_logo_demo_page.dart index 85a8a15..9b01b64 100644 --- a/lib/widget/anim_juejin_logo_demo_page.dart +++ b/lib/widget/anim_juejin_logo_demo_page.dart @@ -2,7 +2,7 @@ import 'package:flutter/material.dart'; import 'package:rive/rive.dart'; class AnimJueJinLogoDemoPage extends StatefulWidget { - const AnimJueJinLogoDemoPage({Key? key}) : super(key: key); + const AnimJueJinLogoDemoPage({super.key}); @override State createState() => _AnimJueJinLogoDemoPageState(); @@ -13,12 +13,10 @@ class _AnimJueJinLogoDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("AnimJueJinLogoDemoPage"), + title: const Text("AnimJueJinLogoDemoPage"), ), - body: Container( - child: RiveAnimation.asset( - 'static/juejin.riv', - ), + body: const RiveAnimation.asset( + 'static/juejin.riv', ), ); } diff --git a/lib/widget/anim_progress_img_demo_page.dart b/lib/widget/anim_progress_img_demo_page.dart index 287b041..b9c4b67 100644 --- a/lib/widget/anim_progress_img_demo_page.dart +++ b/lib/widget/anim_progress_img_demo_page.dart @@ -8,6 +8,8 @@ import 'package:flutter/material.dart'; const radius = 6.0; class AnimProgressImgDemoPage extends StatefulWidget { + const AnimProgressImgDemoPage({super.key}); + @override _AnimProgressImgDemoPageState createState() => _AnimProgressImgDemoPageState(); @@ -25,9 +27,9 @@ class _AnimProgressImgDemoPageState extends State void initState() { super.initState(); - animController = new AnimationController(vsync: this) - ..duration = Duration(milliseconds: 1000); - this.animAnimation = CurvedAnimation( + animController = AnimationController(vsync: this) + ..duration = const Duration(milliseconds: 1000); + animAnimation = CurvedAnimation( parent: animController, curve: Curves.linear, )..addListener(updateState); @@ -49,41 +51,39 @@ class _AnimProgressImgDemoPageState extends State Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("AnimProgressImgDemoPage"), + title: const Text("AnimProgressImgDemoPage"), ), - body: Container( - child: Center( - child: Stack( - children: [ - ClipRRect( - borderRadius: BorderRadius.circular(radius), - child: new Image.asset( - "static/gsy_cat.png", - fit: BoxFit.cover, - width: 300, - height: 200, - ), - ), - SizedBox( + body: Center( + child: Stack( + children: [ + ClipRRect( + borderRadius: BorderRadius.circular(radius), + child: Image.asset( + "static/gsy_cat.png", + fit: BoxFit.cover, width: 300, height: 200, - child: CustomPaint( - painter: AnimProgressPainter( - status: progressType, - animatorValue: animAnimation.value, - finishAnimValue: animAnimation.value, - progress: progress), - ), - ) - ], - ), + ), + ), + SizedBox( + width: 300, + height: 200, + child: CustomPaint( + painter: AnimProgressPainter( + status: progressType, + animatorValue: animAnimation.value, + finishAnimValue: animAnimation.value, + progress: progress), + ), + ) + ], ), ), floatingActionButton: FloatingActionButton( onPressed: () { progress = 0; progressTimer?.cancel(); - progressTimer = Timer.periodic(Duration(milliseconds: 30), (_) { + progressTimer = Timer.periodic(const Duration(milliseconds: 30), (_) { if (progress == 100) { progress = 0; progressTimer?.cancel(); @@ -100,7 +100,7 @@ class _AnimProgressImgDemoPageState extends State animController.reset(); animController.repeat(reverse: true); }, - child: Icon(Icons.play_arrow), + child: const Icon(Icons.play_arrow), ), ); } @@ -141,10 +141,10 @@ class AnimProgressPainter extends CustomPainter { canvas.save(); path.addRRect( - new RRect.fromLTRBR(0, 0, width, height, Radius.circular(radius))); + RRect.fromLTRBR(0, 0, width, height, const Radius.circular(radius))); canvas.clipPath(path); Paint paint = Paint(); - paint.color = Color(0x99000000); + paint.color = const Color(0x99000000); canvas.save(); canvas.translate(width / 2, height / 2); @@ -158,7 +158,7 @@ class AnimProgressPainter extends CustomPainter { Rect.fromCircle(center: Offset.zero, radius: outRadius - 10); try { - if (Platform.isAndroid == true || Platform.isIOS == true) + if (Platform.isAndroid == true || Platform.isIOS == true) { paint.shader = RadialGradient(tileMode: TileMode.mirror, radius: 0.1, colors: [ Colors.transparent, @@ -166,15 +166,17 @@ class AnimProgressPainter extends CustomPainter { Colors.white.withAlpha((255 * animatorValue).toInt()), Colors.transparent ]).createShader(arcRect); + } + // ignore: empty_catches } catch (e) {} - canvas.drawCircle(Offset(0, 0), + canvas.drawCircle(const Offset(0, 0), innRadius + (outRadius - innRadius - 3) * animatorValue, paint); paint.blendMode = BlendMode.dstOut; paint.shader = null; paint.color = Colors.white; - canvas.drawCircle(Offset(0, 0), innRadius, paint); + canvas.drawCircle(const Offset(0, 0), innRadius, paint); paint.blendMode = BlendMode.srcOver; @@ -192,7 +194,7 @@ class AnimProgressPainter extends CustomPainter { Math.pow(width.toDouble(), 2.0) + Math.pow(height.toDouble(), 2.0)); paint.blendMode = BlendMode.dstOut; paint.color = Colors.white; - canvas.drawCircle(Offset(0, 0), + canvas.drawCircle(const Offset(0, 0), (outRadius + (maxRadius / 2 - outRadius) * finishAnimValue), paint); paint.blendMode = BlendMode.srcOver; canvas.restore(); diff --git a/lib/widget/anim_scan_demo_page.dart b/lib/widget/anim_scan_demo_page.dart index d339a6e..9280c3a 100644 --- a/lib/widget/anim_scan_demo_page.dart +++ b/lib/widget/anim_scan_demo_page.dart @@ -6,6 +6,8 @@ import 'package:flutter/material.dart'; import 'package:flutter/physics.dart'; class AnimScanDemoPage extends StatefulWidget { + const AnimScanDemoPage({super.key}); + @override _AnimScanDemoPageState createState() => _AnimScanDemoPageState(); } @@ -35,9 +37,9 @@ class _AnimScanDemoPageState extends State void initState() { super.initState(); - animController = new AnimationController(vsync: this) - ..duration = Duration(milliseconds: 1000); - this.animAnimation = CurvedAnimation( + animController = AnimationController(vsync: this) + ..duration = const Duration(milliseconds: 1000); + animAnimation = CurvedAnimation( parent: animController, curve: Curves.linear, )..addListener(() { @@ -46,9 +48,9 @@ class _AnimScanDemoPageState extends State }); animController.repeat(reverse: true); - imgAnimController = new AnimationController(vsync: this); + imgAnimController = AnimationController(vsync: this); imgAnimation = - imgAnimController.drive(new Tween(begin: 0.8, end: 1.0)); + imgAnimController.drive(Tween(begin: 0.8, end: 1.0)); startImgAnim(); } @@ -87,42 +89,41 @@ class _AnimScanDemoPageState extends State Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("AnimScanDemoPage"), + title: const Text("AnimScanDemoPage"), + ), + body: Center( + child: Stack( + alignment: Alignment.center, + children: [ + SizedBox( + width: 300, + height: 300, + child: CustomPaint( + painter: AnimScanPainter( + rippleCircles: rippleCircles, sweepProgress: sweepProgress), + ), ), - body: Container( - child: Center( - child: Stack( - alignment: Alignment.center, - children: [ - new SizedBox( - width: 300, - height: 300, - child: CustomPaint( - painter: AnimScanPainter( - rippleCircles: rippleCircles, sweepProgress: sweepProgress), + DebounceButton( + onTap: () { + startRipple(300, 300); + startImgAnim(); + }, + radius: 70, + child: ScaleTransition( + scale: imgAnimation as Animation, + child: ClipRRect( + borderRadius: BorderRadius.circular(70), + child: Image.asset( + "static/gsy_cat.png", + fit: BoxFit.cover, + width: 140, + height: 140, ), ), - DebounceButton( - onTap: () { - startRipple(300, 300); - startImgAnim(); - }, - radius: 70, - child: ScaleTransition( - scale: imgAnimation as Animation, - child: ClipRRect( - borderRadius: BorderRadius.circular(70), - child: new Image.asset( - "static/gsy_cat.png", - fit: BoxFit.cover, - width: 140, - height: 140, - ), - ), - ), - ) - ], - )))); + ), + ) + ], + ))); } } @@ -154,12 +155,12 @@ class AnimScanPainter extends CustomPainter { var colors = [ Colors.blueAccent[700], Colors.blue, - Color(0xFFFFF6F6), + const Color(0xFFFFF6F6), Colors.white, ]; var sweepGradient = - SweepGradient(colors: colors as List, stops: [0, 0.001, 0.9, 1]); + SweepGradient(colors: colors as List, stops: const [0, 0.001, 0.9, 1]); /// shader 暂不支持 web if (Platform.isAndroid == true || Platform.isIOS == true) { @@ -178,12 +179,12 @@ class AnimScanPainter extends CustomPainter { canvas.drawCircle(Offset(width / 2, height / 2), radius, backPaint); backPaint.shader = SweepGradient(colors: [ - Color(0xFFFFF6F6).withAlpha(0), - Color(0xFFFFF6F6).withAlpha(10), + const Color(0xFFFFF6F6).withAlpha(0), + const Color(0xFFFFF6F6).withAlpha(10), Colors.white.withAlpha(0), - Color(0xFFFFF6F6).withAlpha(10), + const Color(0xFFFFF6F6).withAlpha(10), Colors.blue, - ], stops: [ + ], stops: const [ 0, 0.001, 0.001, @@ -247,14 +248,14 @@ class DebounceButton extends StatefulWidget { final GestureTapCallback? onTap; final double radius; - DebounceButton({this.child, this.onTap, this.radius = 0}); + const DebounceButton({super.key, this.child, this.onTap, this.radius = 0}); @override _DebounceButtonState createState() => _DebounceButtonState(); } class _DebounceButtonState extends State { - Duration durationTime = Duration(milliseconds: 500); + Duration durationTime = const Duration(milliseconds: 500); Timer? timer; @override @@ -277,7 +278,7 @@ class _DebounceButtonState extends State { setState(() { if (timer == null) { widget.onTap?.call(); - timer = new Timer(durationTime, () { + timer = Timer(durationTime, () { timer = null; }); } diff --git a/lib/widget/anim_switch_layout_demo_page.dart b/lib/widget/anim_switch_layout_demo_page.dart index 9330d04..19b0cdd 100644 --- a/lib/widget/anim_switch_layout_demo_page.dart +++ b/lib/widget/anim_switch_layout_demo_page.dart @@ -1,7 +1,8 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; class AnimSwitchLayoutDemoPage extends StatefulWidget { - const AnimSwitchLayoutDemoPage({Key? key}) : super(key: key); + const AnimSwitchLayoutDemoPage({super.key}); @override State createState() => @@ -50,13 +51,13 @@ class _AnimSwitchLayoutDemoPageState extends State Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("ControllerDemoPage"), + title: const Text("ControllerDemoPage"), ), extendBody: true, body: Center( child: Container( height: 300, - margin: EdgeInsets.symmetric(horizontal: 20), + margin: const EdgeInsets.symmetric(horizontal: 20), child: LayoutBuilder( builder: (_, con) { var f = getIndexPosition(currentIndex % 3, con.biggest); @@ -68,21 +69,27 @@ class _AnimSwitchLayoutDemoPageState extends State PositionItem(f, child: InkWell( onTap: () { - print("red"); + if (kDebugMode) { + print("red"); + } }, child: Container(color: Colors.redAccent), )), PositionItem(s, child: InkWell( onTap: () { - print("green"); + if (kDebugMode) { + print("green"); + } }, child: Container(color: Colors.greenAccent), )), PositionItem(t, child: InkWell( onTap: () { - print("yello"); + if (kDebugMode) { + print("yello"); + } }, child: Container(color: Colors.yellowAccent), )), @@ -107,22 +114,22 @@ class PositionItem extends StatelessWidget { final PositionedItemData data; final Widget child; - const PositionItem(this.data, {required this.child}); + const PositionItem(this.data, {super.key, required this.child}); @override Widget build(BuildContext context) { - return new AnimatedPositioned( - duration: Duration(seconds: 1), + return AnimatedPositioned( + duration: const Duration(seconds: 1), curve: Curves.fastOutSlowIn, - child: new AnimatedContainer( - duration: Duration(seconds: 1), + left: data.left, + top: data.top, + child: AnimatedContainer( + duration: const Duration(seconds: 1), curve: Curves.fastOutSlowIn, width: data.width, height: data.height, child: child, ), - left: data.left, - top: data.top, ); } } diff --git a/lib/widget/anim_text_demo_page.dart b/lib/widget/anim_text_demo_page.dart index b9ab546..d8b40b0 100644 --- a/lib/widget/anim_text_demo_page.dart +++ b/lib/widget/anim_text_demo_page.dart @@ -1,9 +1,10 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:animated_text_kit/animated_text_kit.dart'; class AnimTextDemoPage extends StatefulWidget { - AnimTextDemoPage({Key? key}) : super(key: key); + const AnimTextDemoPage({super.key}); @override _AnimTextDemoPageState createState() => _AnimTextDemoPageState(); @@ -18,7 +19,9 @@ class _AnimTextDemoPageState extends State { void initState() { super.initState(); _examples = animatedTextExamples(onTap: () { - print('Tap Event'); + if (kDebugMode) { + print('Tap Event'); + } setState(() { _tapCount++; }); @@ -33,7 +36,7 @@ class _AnimTextDemoPageState extends State { appBar: AppBar( title: Text( animatedTextExample.label, - style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold), + style: const TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold), ), ), body: Column( @@ -124,7 +127,7 @@ List animatedTextExamples({VoidCallback? onTap}) => height: 100.0, ), DefaultTextStyle( - style: TextStyle( + style: const TextStyle( fontSize: 40.0, fontFamily: 'Horizon', ), diff --git a/lib/widget/anim_tip_demo_page.dart b/lib/widget/anim_tip_demo_page.dart index 273102c..6b1cc36 100644 --- a/lib/widget/anim_tip_demo_page.dart +++ b/lib/widget/anim_tip_demo_page.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; class AnimTipDemoPage extends StatefulWidget { + const AnimTipDemoPage({super.key}); + @override _AnimTipDemoPageState createState() => _AnimTipDemoPageState(); } @@ -12,70 +14,64 @@ class _AnimTipDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("AnimTipDemoPage"), + title: const Text("AnimTipDemoPage"), ), - body: Container( - child: new Column(children: [ - Container( - child: AnimatedSwitcher( - switchInCurve: Cubic(0.4, 0.0, 0.2, 1.0), - switchOutCurve: Cubic(1.0, 0.1, 1.0, 0.1), - transitionBuilder: (child, anim) { - return SlideTransition( - child: child, - position: Tween( - begin: Offset(0.0, -1.0), - end: Offset(0.0, 0.0), - ).animate(anim)); - }, - duration: Duration(milliseconds: 500), - child: showTipItem - ? Container( - alignment: Alignment.centerLeft, - width: MediaQuery.sizeOf(context).width, - height: 70, - key: ValueKey("TipItem"), - color: Colors.amber, - child: new Row( - children: [ - new Icon(Icons.ac_unit, - color: Colors.white, size: 13), - new SizedBox( - width: 10, - ), - new Text( - "StickText", - style: TextStyle(color: Colors.white), - ), - ], + body: Column(children: [ + AnimatedSwitcher( + switchInCurve: const Cubic(0.4, 0.0, 0.2, 1.0), + switchOutCurve: const Cubic(1.0, 0.1, 1.0, 0.1), + transitionBuilder: (child, anim) { + return SlideTransition( + position: Tween( + begin: const Offset(0.0, -1.0), + end: const Offset(0.0, 0.0), + ).animate(anim), + child: child); + }, + duration: const Duration(milliseconds: 500), + child: showTipItem + ? Container( + alignment: Alignment.centerLeft, + width: MediaQuery.sizeOf(context).width, + height: 70, + key: const ValueKey("TipItem"), + color: Colors.amber, + child: const Row( + children: [ + Icon(Icons.ac_unit, + color: Colors.white, size: 13), + SizedBox( + width: 10, ), - ) - : new Container( - key: ValueKey("hideItem"), - ), - ), - ), - new Expanded( - child: new Container( - child: new Center( - child: new TextButton( - onPressed: () { - setState(() { - showTipItem = true; - }); - Future.delayed(Duration(seconds: 1), () { - setState(() { - showTipItem = false; - }); - }); - }, - child: new Text("Click Me"), + Text( + "StickText", + style: TextStyle(color: Colors.white), + ), + ], + ), + ) + : Container( + key: const ValueKey("hideItem"), ), - ), + ), + Expanded( + child: Center( + child: TextButton( + onPressed: () { + setState(() { + showTipItem = true; + }); + Future.delayed(const Duration(seconds: 1), () { + setState(() { + showTipItem = false; + }); + }); + }, + child: const Text("Click Me"), ), - ) - ]), - ), + ), + ) + ]), ); } } diff --git a/lib/widget/anima_demo_page.dart b/lib/widget/anima_demo_page.dart index bc7ec6f..bed34be 100644 --- a/lib/widget/anima_demo_page.dart +++ b/lib/widget/anima_demo_page.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; class AnimaDemoPage extends StatefulWidget { + const AnimaDemoPage({super.key}); + @override _AnimaDemoPageState createState() => _AnimaDemoPageState(); } @@ -17,7 +19,7 @@ class _AnimaDemoPageState extends State void initState() { super.initState(); controller1 = - new AnimationController(vsync: this, duration: Duration(seconds: 3)); + AnimationController(vsync: this, duration: const Duration(seconds: 3)); animation1 = Tween(begin: 0.0, end: 200.0).animate(controller1) ..addListener(() { @@ -39,22 +41,20 @@ class _AnimaDemoPageState extends State Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("AnimaDemoPage"), + title: const Text("AnimaDemoPage"), ), ///用封装好的 Transition 做动画 - body: new RotationTransition( + body: RotationTransition( turns: animation2 as Animation, - child: new Container( - child: Center( - child: new Container( - height: 200, - width: 200, - color: Colors.greenAccent, - child: CustomPaint( - ///直接使用值做动画 - foregroundPainter: _AnimationPainter(animation1), - ), + child: Center( + child: Container( + height: 200, + width: 200, + color: Colors.greenAccent, + child: CustomPaint( + ///直接使用值做动画 + foregroundPainter: _AnimationPainter(animation1), ), ), ), @@ -64,7 +64,7 @@ class _AnimaDemoPageState extends State } class _AnimationPainter extends CustomPainter { - Paint _paint = new Paint(); + final Paint _paint = Paint(); Animation? animation; @@ -76,7 +76,7 @@ class _AnimationPainter extends CustomPainter { ..color = Colors.redAccent ..strokeWidth = 4 ..style = PaintingStyle.stroke; - canvas.drawCircle(Offset(100, 100), animation!.value * 1.5, _paint); + canvas.drawCircle(const Offset(100, 100), animation!.value * 1.5, _paint); } @override diff --git a/lib/widget/anima_demo_page2.dart b/lib/widget/anima_demo_page2.dart index a57a1f4..a6e46e9 100644 --- a/lib/widget/anima_demo_page2.dart +++ b/lib/widget/anima_demo_page2.dart @@ -4,7 +4,10 @@ import 'dart:ui'; import 'package:flutter/material.dart'; class AnimaDemoPage2 extends StatefulWidget { + const AnimaDemoPage2({super.key}); + @override + // ignore: library_private_types_in_public_api _AnimaDemoPageState2 createState() => _AnimaDemoPageState2(); } @@ -19,7 +22,7 @@ class _AnimaDemoPageState2 extends State controller = AnimationController( vsync: this, - duration: Duration(milliseconds: 500), + duration: const Duration(milliseconds: 500), ); animation = CurvedAnimation( @@ -38,7 +41,7 @@ class _AnimaDemoPageState2 extends State Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("AnimaDemoPage2"), + title: const Text("AnimaDemoPage2"), ), body: Container( color: Colors.blueAccent, @@ -54,7 +57,7 @@ class _AnimaDemoPageState2 extends State height: 250, width: 250, color: Colors.greenAccent, - child: new Text("我我我我我我我我我我我说"), + child: const Text("我我我我我我我我我我我说"), ), ), ), @@ -68,7 +71,7 @@ class _AnimaDemoPageState2 extends State controller.forward(); } }, - child: new Text("点我"), + child: const Text("点我"), ), ); } @@ -85,7 +88,7 @@ class CRAnimation extends StatelessWidget { final Animation? animation; - CRAnimation({ + const CRAnimation({super.key, required this.child, required this.animation, this.offset, @@ -105,7 +108,7 @@ class CRAnimation extends StatelessWidget { maxR: maxR, offset: offset, ), - child: this.child, + child: child, ); }, ); @@ -129,7 +132,7 @@ class AnimationClipper extends CustomClipper { }); @override - bool shouldReclip(old) => true; + bool shouldReclip(oldClipper) => true; @override Path getClip(Size size) { diff --git a/lib/widget/anima_demo_page4.dart b/lib/widget/anima_demo_page4.dart index db9a495..c50cf82 100644 --- a/lib/widget/anima_demo_page4.dart +++ b/lib/widget/anima_demo_page4.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; class AnimaDemoPage4 extends StatefulWidget { + const AnimaDemoPage4({super.key}); + @override _AnimaDemoPageState createState() => _AnimaDemoPageState(); } @@ -12,22 +14,23 @@ class _AnimaDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text('AnimaDemoPage4'), + title: const Text('AnimaDemoPage4'), actions: [ AnimatedSwitcher( transitionBuilder: (child, anim) { - return ScaleTransition(child: child, scale: anim); + return ScaleTransition(scale: anim, child: child); }, - duration: Duration(milliseconds: 300), + duration: const Duration(milliseconds: 300), child: IconButton( key: ValueKey(iconData), icon: Icon(iconData), onPressed: () { setState(() { - if (iconData == Icons.clear) + if (iconData == Icons.clear) { iconData = Icons.add; - else + } else { iconData = Icons.clear; + } }); }), ) @@ -37,26 +40,28 @@ class _AnimaDemoPageState extends State { floatingActionButton: FloatingActionButton( onPressed: () { setState(() { - if (iconData == Icons.clear) + if (iconData == Icons.clear) { iconData = Icons.add; - else + } else { iconData = Icons.clear; + } }); }, child: AnimatedSwitcher( transitionBuilder: (child, anim) { - return ScaleTransition(child: child, scale: anim); + return ScaleTransition(scale: anim, child: child); }, - duration: Duration(milliseconds: 300), + duration: const Duration(milliseconds: 300), child: IconButton( key: ValueKey(iconData), icon: Icon(iconData), onPressed: () { setState(() { - if (iconData == Icons.clear) + if (iconData == Icons.clear) { iconData = Icons.add; - else + } else { iconData = Icons.clear; + } }); }), ), diff --git a/lib/widget/anima_demo_page5.dart b/lib/widget/anima_demo_page5.dart index 917aa29..31622f3 100644 --- a/lib/widget/anima_demo_page5.dart +++ b/lib/widget/anima_demo_page5.dart @@ -3,50 +3,50 @@ import 'package:flutter/material.dart'; const String testString = "Hello GSY,欢迎你的交流"; class AnimaDemoPage5 extends StatefulWidget { + const AnimaDemoPage5({super.key}); + @override _AnimaDemoPageState createState() => _AnimaDemoPageState(); } class _AnimaDemoPageState extends State with TickerProviderStateMixin { - List _charList = []; - List _controllerList =[]; - List _moveAnimation = []; + final List _charList = []; + final List _controllerList =[]; + final List _moveAnimation = []; bool played = false; bool playing = false; @override void initState() { - testString.codeUnits.forEach((value) { + for (var value in testString.codeUnits) { _charList.add(String.fromCharCode(value)); var controller = AnimationController( - vsync: this, duration: Duration(milliseconds: 600)); + vsync: this, duration: const Duration(milliseconds: 600)); _controllerList.add(controller); _moveAnimation.add(CurvedAnimation( parent: controller, curve: Curves.easeInOutExpo, )); - }); + } super.initState(); } @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar(title: Text('AnimaDemoPage5')), - body: Container( - child: new Center( - child: Wrap( - children: List.generate(_charList.length, (i) { - return AnimatedText( - animation: _moveAnimation[i], - child: Text( - _charList[i], - style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), - )); - }), - ), + appBar: AppBar(title: const Text('AnimaDemoPage5')), + body: Center( + child: Wrap( + children: List.generate(_charList.length, (i) { + return AnimatedText( + animation: _moveAnimation[i], + child: Text( + _charList[i], + style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), + )); + }), ), ), floatingActionButton: FloatingActionButton( @@ -54,12 +54,13 @@ class _AnimaDemoPageState extends State if (playing) { return; } - if (played) + if (played) { back(); - else + } else { play(); + } }, - child: Icon(Icons.play_arrow), + child: const Icon(Icons.play_arrow), ), ); } @@ -101,7 +102,7 @@ class AnimatedText extends AnimatedWidget { final Tween _opacityAnim = Tween(begin: 0, end: 1); final Widget? child; - AnimatedText({required Animation animation, this.child}) + AnimatedText({super.key, required Animation animation, this.child}) : super(listenable: animation); _getOpacity() { @@ -121,7 +122,7 @@ class AnimatedText extends AnimatedWidget { opacity: _getOpacity(), child: SlideTransition( position: - Tween(begin: Offset(0, 5), end: Offset(0, 0)).animate(listenable as Animation), + Tween(begin: const Offset(0, 5), end: const Offset(0, 0)).animate(listenable as Animation), child: child, ), ); diff --git a/lib/widget/animation_container_demo_page.dart b/lib/widget/animation_container_demo_page.dart index d7893e3..cd53b94 100644 --- a/lib/widget/animation_container_demo_page.dart +++ b/lib/widget/animation_container_demo_page.dart @@ -4,6 +4,8 @@ import 'package:flutter/material.dart'; ///来着 [Flutter 社区 公众号] 的动画例子 class AnimationContainerDemoPage extends StatefulWidget { + const AnimationContainerDemoPage({super.key}); + @override _AnimationContainerDemoPageState createState() => _AnimationContainerDemoPageState(); } @@ -21,7 +23,7 @@ class _AnimationContainerDemoPageState extends State Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text('AnimationContainerDemoPage Demo'), + title: const Text('AnimationContainerDemoPage Demo'), ), body: Center( child: AnimatedContainer( @@ -33,13 +35,13 @@ class _AnimationContainerDemoPageState extends State borderRadius: _borderRadius, ), // Define how long the animation should take. - duration: Duration(seconds: 1), + duration: const Duration(seconds: 1), // Provide an optional curve to make the animation feel smoother. curve: Curves.fastOutSlowIn, ), ), floatingActionButton: FloatingActionButton( - child: Icon(Icons.play_arrow), + child: const Icon(Icons.play_arrow), // When the user taps the button onPressed: () { // Use setState to rebuild the widget with new values. diff --git a/lib/widget/arc_seek_bar_demo_page.dart b/lib/widget/arc_seek_bar_demo_page.dart index cfa238a..cbaa957 100644 --- a/lib/widget/arc_seek_bar_demo_page.dart +++ b/lib/widget/arc_seek_bar_demo_page.dart @@ -5,6 +5,8 @@ import 'dart:ui'; import 'package:flutter/material.dart'; class ArcSeekBarDemoPage extends StatefulWidget { + const ArcSeekBarDemoPage({super.key}); + @override _ArcSeekBarDemoPageState createState() => _ArcSeekBarDemoPageState(); } @@ -14,7 +16,7 @@ class _ArcSeekBarDemoPageState extends State double progress = 0; final double rotateAngle = 90; final double openAngle = 120; - final Size size = Size(300, 300); + final Size size = const Size(300, 300); onTouch(DragUpdateDetails d) { var x = d.localPosition.dx; @@ -59,21 +61,19 @@ class _ArcSeekBarDemoPageState extends State Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("ArcSeekBarDemoPage"), + title: const Text("ArcSeekBarDemoPage"), ), - body: Container( - child: Center( - child: GestureDetector( - onPanUpdate: onTouch, - child: SizedBox( - height: size.width, - width: size.height, - child: CustomPaint( - painter: new ArcSeekBarPainter( - progress: progress, - rotateAngle: rotateAngle, - openAngle: openAngle), - ), + body: Center( + child: GestureDetector( + onPanUpdate: onTouch, + child: SizedBox( + height: size.width, + width: size.height, + child: CustomPaint( + painter: ArcSeekBarPainter( + progress: progress, + rotateAngle: rotateAngle, + openAngle: openAngle), ), ), ), @@ -105,8 +105,8 @@ class ArcSeekBarPainter extends CustomPainter { late Rect content; late double startAngle; late double sweepAngle; - Offset tempPos = Offset(0, 0); - Offset tempTan = Offset(0, 0); + Offset tempPos = const Offset(0, 0); + Offset tempTan = const Offset(0, 0); PathMetric? seekPathMeasure; @@ -125,8 +125,8 @@ class ArcSeekBarPainter extends CustomPainter { late List arcColors; void initData() { - seekPath = new Path(); - borderPath = new Path(); + seekPath = Path(); + borderPath = Path(); arcColors = [Colors.blueAccent, Colors.pinkAccent, Colors.amberAccent]; } @@ -138,7 +138,7 @@ class ArcSeekBarPainter extends CustomPainter { } void initArcPaint() { - arcPaint = new Paint(); + arcPaint = Paint(); arcPaint.isAntiAlias = true; arcPaint.strokeWidth = 40; arcPaint.style = PaintingStyle.stroke; @@ -146,7 +146,7 @@ class ArcSeekBarPainter extends CustomPainter { } void initThumbPaint() { - thumbPaint = new Paint(); + thumbPaint = Paint(); thumbPaint.isAntiAlias = true; thumbPaint.color = Colors.white; thumbPaint.strokeWidth = borderWidth; @@ -155,7 +155,7 @@ class ArcSeekBarPainter extends CustomPainter { } void initBorderPaint() { - borderPaint = new Paint(); + borderPaint = Paint(); borderPaint.isAntiAlias = true; borderPaint.color = Colors.white; borderPaint.strokeWidth = 0; @@ -188,7 +188,7 @@ class ArcSeekBarPainter extends CustomPainter { startY = 0; } - content = new Rect.fromLTRB( + content = Rect.fromLTRB( startX + fix, startY + fix, startX + edgeLength, startY + edgeLength); centerX = content.center.dx; centerY = content.center.dy; @@ -231,8 +231,10 @@ class ArcSeekBarPainter extends CustomPainter { } var sweepGradient = SweepGradient(colors: arcColors, stops: pos); try { - if (Platform.isIOS == true || Platform.isAndroid == true) + if (Platform.isIOS == true || Platform.isAndroid == true) { arcPaint.shader = sweepGradient.createShader(Offset.zero & size); + } + // ignore: empty_catches } catch (e) {} } diff --git a/lib/widget/async_to_sync_call_page.dart b/lib/widget/async_to_sync_call_page.dart index 358a03c..3b2866e 100644 --- a/lib/widget/async_to_sync_call_page.dart +++ b/lib/widget/async_to_sync_call_page.dart @@ -1,9 +1,10 @@ import 'dart:async'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; class AsyncToSyncCallPage extends StatefulWidget { - const AsyncToSyncCallPage({Key? key}) : super(key: key); + const AsyncToSyncCallPage({super.key}); @override State createState() => _AsyncToSyncCallPageState(); @@ -43,24 +44,32 @@ class _AsyncToSyncCallPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("AsyncToSyncCallPage"), + title: const Text("AsyncToSyncCallPage"), ), floatingActionButton: FloatingActionButton( onPressed: () { - print("Start······Waiting"); + if (kDebugMode) { + print("Start······Waiting"); + } _syncWait(() async { - await Future.delayed(Duration(seconds: 4)); - print("Finish First"); + await Future.delayed(const Duration(seconds: 4)); + if (kDebugMode) { + print("Finish First"); + } }); _syncWait(() async { - await Future.delayed(Duration(seconds: 2)); - print("Finish Tow"); + await Future.delayed(const Duration(seconds: 2)); + if (kDebugMode) { + print("Finish Tow"); + } }); _syncWait(() async { - await Future.delayed(Duration(seconds: 1)); - print("Finish Three"); + await Future.delayed(const Duration(seconds: 1)); + if (kDebugMode) { + print("Finish Three"); + } }); }, ), diff --git a/lib/widget/blur_demo_page.dart b/lib/widget/blur_demo_page.dart index 0036bc5..07a949f 100644 --- a/lib/widget/blur_demo_page.dart +++ b/lib/widget/blur_demo_page.dart @@ -3,50 +3,50 @@ import 'dart:ui'; import 'package:flutter/material.dart'; class BlurDemoPage extends StatelessWidget { + const BlurDemoPage({super.key}); + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("BlurDemoPage"), + title: const Text("BlurDemoPage"), ), - body: new Container( - child: Stack( - children: [ - Positioned( - top: 0, - bottom: 0, - left: 0, - right: 0, - child: new Image.asset( - "static/gsy_cat.png", - fit: BoxFit.cover, - width: MediaQuery.sizeOf(context).width, - height: MediaQuery.sizeOf(context).height, - ), + body: Stack( + children: [ + Positioned( + top: 0, + bottom: 0, + left: 0, + right: 0, + child: Image.asset( + "static/gsy_cat.png", + fit: BoxFit.cover, + width: MediaQuery.sizeOf(context).width, + height: MediaQuery.sizeOf(context).height, ), - new Center( - child: new Container( - width: 200, - height: 200, - child: ClipRRect( - borderRadius: BorderRadius.circular(15.0), - child: BackdropFilter( - filter: ImageFilter.blur(sigmaX: 8.0, sigmaY: 8.0), - child: new Row( - mainAxisSize: MainAxisSize.max, - crossAxisAlignment: CrossAxisAlignment.center, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - new Icon(Icons.ac_unit), - new Text("哇!!") - ], - ), + ), + Center( + child: SizedBox( + width: 200, + height: 200, + child: ClipRRect( + borderRadius: BorderRadius.circular(15.0), + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 8.0, sigmaY: 8.0), + child: const Row( + mainAxisSize: MainAxisSize.max, + crossAxisAlignment: CrossAxisAlignment.center, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.ac_unit), + Text("哇!!") + ], ), ), ), - ) - ], - ), + ), + ) + ], ), ); } diff --git a/lib/widget/book_page/book_page.dart b/lib/widget/book_page/book_page.dart index 3bccbfd..bfdacd6 100644 --- a/lib/widget/book_page/book_page.dart +++ b/lib/widget/book_page/book_page.dart @@ -4,6 +4,8 @@ import 'package:gsy_flutter_demo/widget/book_page/cal_point.dart'; import 'book_painter.dart'; class BookPage extends StatefulWidget { + const BookPage({super.key}); + @override _BookPageState createState() => _BookPageState(); } @@ -93,8 +95,8 @@ class _BookPageState extends State } _initCancelAnim() { - animationController = new AnimationController( - vsync: this, duration: Duration(milliseconds: 300)); + animationController = AnimationController( + vsync: this, duration: const Duration(milliseconds: 300)); cancelAnim = animationController.drive(CurveTween(curve: Curves.linear)); cancelAnim ..addListener(() { @@ -136,9 +138,9 @@ class _BookPageState extends State Color bgColor = Colors.tealAccent; return Scaffold( appBar: AppBar( - title: new Text("BookPage"), + title: const Text("BookPage"), ), - body: Container( + body: SizedBox( height: height, width: width, child: GestureDetector( diff --git a/lib/widget/book_page/book_painter.dart b/lib/widget/book_page/book_painter.dart index d07c84a..e14237e 100644 --- a/lib/widget/book_page/book_painter.dart +++ b/lib/widget/book_page/book_painter.dart @@ -104,19 +104,19 @@ class BookPainter extends CustomPainter { f = CalPoint(); ///其他坐标 - g = new CalPoint(); - e = new CalPoint(); - h = new CalPoint(); - c = new CalPoint(); - j = new CalPoint(); - b = new CalPoint(); - k = new CalPoint(); - d = new CalPoint(); - i = new CalPoint(); - - pathB = new Path(); - pathA = new Path(); - pathC = new Path(); + g = CalPoint(); + e = CalPoint(); + h = CalPoint(); + c = CalPoint(); + j = CalPoint(); + b = CalPoint(); + k = CalPoint(); + d = CalPoint(); + i = CalPoint(); + + pathB = Path(); + pathA = Path(); + pathC = Path(); } _selectCalPoint(CalPoint cur, CalPoint pre, {bool? limitAngle = true}) { @@ -171,24 +171,24 @@ class BookPainter extends CustomPainter { } _initPaintAndPath() { - bgPaint = new Paint(); + bgPaint = Paint(); bgPaint.color = Colors.white; - pathAPaint = new Paint(); + pathAPaint = Paint(); pathAPaint.color = bgColor; pathAPaint.isAntiAlias = true; - pathCPaint = new Paint(); + pathCPaint = Paint(); pathCPaint.color = frontColor; pathCPaint.blendMode = BlendMode.dstATop; pathCPaint.isAntiAlias = true; - pathBPaint = new Paint(); + pathBPaint = Paint(); pathBPaint.color = Colors.tealAccent; pathBPaint.blendMode = BlendMode.dstATop; pathBPaint.isAntiAlias = true; - pathB = new Path(); + pathB = Path(); } void onDraw(Canvas canvas, Size size) async { @@ -240,7 +240,7 @@ class BookPainter extends CustomPainter { canvas.restore(); canvas.save(); - var gradientColors = [Color(0x01333333), Color(0x33333333)]; + var gradientColors = [const Color(0x01333333), const Color(0x33333333)]; double? left; double? right; @@ -260,10 +260,10 @@ class BookPainter extends CustomPainter { gradient = ui.Gradient.linear( Offset(right, top), Offset(left!, top), gradientColors); } - Paint paint = new Paint()..shader = gradient; + Paint paint = Paint()..shader = gradient; //裁剪出我们需要的区域 - Path mPath = new Path(); + Path mPath = Path(); mPath.moveTo(a.x! - Math.max(rPathAShadowDis, lPathAShadowDis) / 2, a.y!); mPath.lineTo(d.x!, d.y!); mPath.lineTo(e.x!, e.y!); @@ -285,8 +285,8 @@ class BookPainter extends CustomPainter { canvas.save(); var gradientColors = [ - Color(0x33333333), - Color(0x01333333), + const Color(0x33333333), + const Color(0x01333333), ]; double viewDiagonalLength = _hypot(viewWidth!, viewHeight!) as double; //view对角线长度 @@ -308,9 +308,9 @@ class BookPainter extends CustomPainter { gradient = ui.Gradient.linear( Offset(left, top!), Offset(left, bottom), gradientColors); } - Paint paint = new Paint()..shader = gradient; + Paint paint = Paint()..shader = gradient; - Path mPath = new Path(); + Path mPath = Path(); mPath.moveTo(a.x! - Math.max(rPathAShadowDis, lPathAShadowDis) / 2, a.y!); // mPath.lineTo(i.x,i.y); mPath.lineTo(h.x!, h.y!); @@ -330,7 +330,7 @@ class BookPainter extends CustomPainter { canvas.restore(); canvas.save(); - var radientColors = [Color(0x01333333), Color(0x44333333)]; //渐变颜色数组 + var radientColors = [const Color(0x01333333), const Color(0x44333333)]; //渐变颜色数组 double maxShadowWidth = 30; //阴影矩形最大的宽度 double left = (a.x! - Math.min(maxShadowWidth, (rPathAShadowDis / 2))); @@ -340,7 +340,7 @@ class BookPainter extends CustomPainter { ui.Gradient gradient = ui.Gradient.linear( Offset(left, top), Offset(right, top), radientColors); - Paint paint = new Paint()..shader = gradient; + Paint paint = Paint()..shader = gradient; canvas.clipPath(pathA); @@ -370,7 +370,7 @@ class BookPainter extends CustomPainter { } void _drawPathBShadow(Canvas canvas) { - var gradientColors = [Color(0xf0111111), Color(0x00000000)]; //渐变颜色数组 + var gradientColors = [const Color(0xf0111111), const Color(0x00000000)]; //渐变颜色数组 int elevation = 6; int deepOffset = 0; //深色端的偏移值 int lightOffset = 0; //浅色端的偏移值 @@ -397,7 +397,7 @@ class BookPainter extends CustomPainter { Offset(right, top), Offset(left, top), gradientColors); } - Paint paint = new Paint() + Paint paint = Paint() //..color = Colors.black.withAlpha(80); //..blendMode = BlendMode.srcOver ..shader = gradient; @@ -459,7 +459,7 @@ class BookPainter extends CustomPainter { } void _drawPathCShadow(Canvas canvas) { - var gradientColors = [Color(0x00333333), Color(0xff111111)]; //渐变颜色数组 + var gradientColors = [const Color(0x00333333), const Color(0xff111111)]; //渐变颜色数组 int deepOffset = 1; //深色端的偏移值 int lightOffset = -30; //浅色端的偏移值 @@ -486,7 +486,7 @@ class BookPainter extends CustomPainter { gradient = ui.Gradient.linear( Offset(right, top), Offset(left, top), gradientColors); } - Paint paint = new Paint()..shader = gradient; + Paint paint = Paint()..shader = gradient; canvas.translate(c.x!, c.y!); canvas.rotate(Math.atan2(e.x! - f.x!, h.y! - f.y!)); @@ -621,8 +621,8 @@ class BookPainter extends CustomPainter { ///计算C点的X值 _calcPointCX(CalPoint a, CalPoint f) { CalPoint g, e; - g = new CalPoint(); - e = new CalPoint(); + g = CalPoint(); + e = CalPoint(); g.x = (a.x! + f.x!) / 2; g.y = (a.y! + f.y!) / 2; diff --git a/lib/widget/bottom_anim_nav_page.dart b/lib/widget/bottom_anim_nav_page.dart index 85e1a61..21bc454 100644 --- a/lib/widget/bottom_anim_nav_page.dart +++ b/lib/widget/bottom_anim_nav_page.dart @@ -1,10 +1,14 @@ import 'dart:math' as math; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_swiper_view/flutter_swiper_view.dart'; +// ignore: implementation_imports import 'package:flutter_swiper_view/src/transformer_page_view.dart'; class BottomAnimNavPage extends StatefulWidget { + const BottomAnimNavPage({super.key}); + @override _BottomAnimNavPageState createState() => _BottomAnimNavPageState(); } @@ -21,7 +25,7 @@ class _BottomAnimNavPageState extends State void initState() { super.initState(); controller = AnimationController(vsync: this) - ..duration = Duration(milliseconds: 500); + ..duration = const Duration(milliseconds: 500); animation = Tween(begin: 0.0, end: 1.0).animate(controller); } @@ -30,7 +34,7 @@ class _BottomAnimNavPageState extends State return Scaffold( backgroundColor: Theme.of(context).primaryColorDark, appBar: AppBar( - title: new Text("ViewPagerDemoPage"), + title: const Text("ViewPagerDemoPage"), ), body: GestureDetector( behavior: HitTestBehavior.opaque, @@ -39,7 +43,7 @@ class _BottomAnimNavPageState extends State }, child: Container( alignment: Alignment.bottomCenter, - margin: EdgeInsets.only(bottom: 50), + margin: const EdgeInsets.only(bottom: 50), child: Builder( builder: (context) { return TextButton( @@ -52,7 +56,7 @@ class _BottomAnimNavPageState extends State context: context, backgroundColor: Colors.transparent, builder: (context) { - return new Container( + return SizedBox( height: 300, child: Stack( children: [ @@ -73,7 +77,7 @@ class _BottomAnimNavPageState extends State itemBuilder: (BuildContext context, int index) { return ScaleTransition( scale: animation as Animation, - child: new Container( + child: Container( decoration: BoxDecoration( color: Colors.red, shape: BoxShape.circle, @@ -84,16 +88,18 @@ class _BottomAnimNavPageState extends State (index == this.index) ? 5 : 10), child: InkWell( onTap: () { - print("##### $index"); + if (kDebugMode) { + print("##### $index"); + } }, focusColor: Colors.transparent, hoverColor: Colors.transparent, highlightColor: Colors.transparent, splashColor: Colors.transparent, - child: new Center( - child: new Text( + child: Center( + child: Text( "$index", - style: new TextStyle( + style: const TextStyle( fontSize: 20.0, color: Colors.white), ), @@ -114,7 +120,7 @@ class _BottomAnimNavPageState extends State controller.reset(); controller.forward(); }, - child: new Text( + child: const Text( "Show", style: TextStyle(fontSize: 22, color: Colors.white), ), @@ -137,12 +143,11 @@ class AngleTransformer extends PageTransformer { _radius = radius; @override - Widget transform(Widget item, TransformInfo info) { + Widget transform(Widget child, TransformInfo info) { double position = info.position!; - Widget child = item; var dx = _horizontalOffset * (position.abs() * 10); - var dy; + double dy; if (dx <= _radius) { dy = _radius - math.sqrt((_radius * _radius) - (dx * dx)); } else { @@ -153,12 +158,12 @@ class AngleTransformer extends PageTransformer { double fadeFactor = (1 - position.abs()) * (1 - _fade); double opacity = _fade + fadeFactor; - child = new Opacity( + child = Opacity( opacity: opacity, child: child, ); - child = new Transform.translate( + child = Transform.translate( offset: Offset(position.isNegative ? -dx : dx, dy), child: child, ); diff --git a/lib/widget/bubble/bubble_demo_page.dart b/lib/widget/bubble/bubble_demo_page.dart index e4b142d..2a72c77 100644 --- a/lib/widget/bubble/bubble_demo_page.dart +++ b/lib/widget/bubble/bubble_demo_page.dart @@ -16,6 +16,8 @@ class BubbleDemoPage extends StatelessWidget { final GlobalKey button3Key = GlobalKey(); final GlobalKey button4Key = GlobalKey(); + BubbleDemoPage({super.key}); + getX(GlobalKey key) { RenderBox renderBox = key.currentContext!.findRenderObject() as RenderBox; double dx = renderBox.localToGlobal(Offset.zero).dx; @@ -102,16 +104,16 @@ class BubbleDemoPage extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("BubbleDemoPage"), + title: const Text("BubbleDemoPage"), ), body: Container( width: MediaQuery.sizeOf(context).width, height: MediaQuery.sizeOf(context).height, - margin: EdgeInsets.all(15), - child: new Stack( + margin: const EdgeInsets.all(15), + child: Stack( key: contentKey, children: [ - new MaterialButton( + MaterialButton( key: button1Key, onPressed: () { showDialog( @@ -129,8 +131,9 @@ class BubbleDemoPage extends StatelessWidget { }, color: Colors.blue, ), - new Positioned( - child: new MaterialButton( + Positioned( + left: MediaQuery.sizeOf(context).width / 2, + child: MaterialButton( key: button2Key, onPressed: () { showDialog( @@ -147,10 +150,11 @@ class BubbleDemoPage extends StatelessWidget { }); }, color: Colors.greenAccent, - ), - left: MediaQuery.sizeOf(context).width / 2), - new Positioned( - child: new MaterialButton( + )), + Positioned( + left: MediaQuery.sizeOf(context).width / 5, + top: MediaQuery.sizeOf(context).height / 4 * 3, + child: MaterialButton( key: button3Key, onPressed: () { showDialog( @@ -168,11 +172,14 @@ class BubbleDemoPage extends StatelessWidget { }, color: Colors.yellow, ), - left: MediaQuery.sizeOf(context).width / 5, - top: MediaQuery.sizeOf(context).height / 4 * 3, ), - new Positioned( - child: new MaterialButton( + Positioned( + left: MediaQuery.sizeOf(context).width / 2 - + Theme.of(context).buttonTheme.minWidth / 2, + top: MediaQuery.sizeOf(context).height / 2 - + MediaQuery.paddingOf(context).top - + kToolbarHeight, + child: MaterialButton( key: button4Key, onPressed: () { showDialog( @@ -190,11 +197,6 @@ class BubbleDemoPage extends StatelessWidget { }, color: Colors.redAccent, ), - left: MediaQuery.sizeOf(context).width / 2 - - Theme.of(context).buttonTheme.minWidth / 2, - top: MediaQuery.sizeOf(context).height / 2 - - MediaQuery.paddingOf(context).top - - kToolbarHeight, ), ], ), @@ -225,8 +227,8 @@ class BubbleDialog extends StatelessWidget { final VoidCallback? voidCallback; - BubbleDialog(this.text, - {this.width, + const BubbleDialog(this.text, + {super.key, this.width, this.height, this.radius = 4, this.arrowLocation = ArrowLocation.BOTTOM, @@ -240,9 +242,9 @@ class BubbleDialog extends StatelessWidget { @override Widget build(BuildContext context) { - return new Scaffold( + return Scaffold( backgroundColor: Colors.transparent, - body: new InkWell( + body: InkWell( splashColor: Colors.transparent, highlightColor: Colors.transparent, onTap: () { diff --git a/lib/widget/bubble/bubble_painter.dart b/lib/widget/bubble/bubble_painter.dart index 95584af..9d45338 100644 --- a/lib/widget/bubble/bubble_painter.dart +++ b/lib/widget/bubble/bubble_painter.dart @@ -4,8 +4,8 @@ import 'dart:math' as Math; ///绘制气泡背景 class BubblePainter extends CustomPainter { Rect? mRect; - Path mPath = new Path(); - Paint mPaint = new Paint(); + Path mPath = Path(); + Paint mPaint = Paint(); late double mArrowWidth; double? mAngle; late double mArrowHeight; @@ -16,14 +16,14 @@ class BubblePainter extends CustomPainter { Color? bubbleColor; BubblePainter(BubbleBuilder builder) { - this.mAngle = builder.mAngle; - this.mArrowHeight = builder.mArrowHeight; - this.mArrowWidth = builder.mArrowWidth; - this.mArrowPosition = builder.mArrowPosition; - this.bubbleColor = builder.bubbleColor; - this.mArrowLocation = builder.mArrowLocation; - this.bubbleType = builder.bubbleType; - this.mArrowCenter = builder.arrowCenter; + mAngle = builder.mAngle; + mArrowHeight = builder.mArrowHeight; + mArrowWidth = builder.mArrowWidth; + mArrowPosition = builder.mArrowPosition; + bubbleColor = builder.bubbleColor; + mArrowLocation = builder.mArrowLocation; + bubbleType = builder.bubbleType; + mArrowCenter = builder.arrowCenter; } @override @@ -63,7 +63,7 @@ class BubblePainter extends CustomPainter { default: break; } - mRect ??= new Rect.fromLTRB(0, 0, size.width, size.height); + mRect ??= Rect.fromLTRB(0, 0, size.width, size.height); setUpPath(mArrowLocation, mPath); canvas.drawPath(mPath, mPaint); } @@ -175,7 +175,7 @@ class BubbleBuilder { bool arrowCenter = true; build() { - return new BubblePainter(this); + return BubblePainter(this); } } diff --git a/lib/widget/bubble/bubble_tip_widget.dart b/lib/widget/bubble/bubble_tip_widget.dart index 30b7d75..94c9ec0 100644 --- a/lib/widget/bubble/bubble_tip_widget.dart +++ b/lib/widget/bubble/bubble_tip_widget.dart @@ -28,7 +28,7 @@ class BubbleTipWidget extends StatefulWidget { final VoidCallback? voidCallback; const BubbleTipWidget( - {this.width, + {super.key, this.width, this.height, this.radius, this.text = "", @@ -52,10 +52,6 @@ class _BubbleTipWidgetState extends State super.initState(); } - @override - void dispose() { - super.dispose(); - } @override Widget build(BuildContext context) { @@ -139,7 +135,7 @@ class _BubbleTipWidgetState extends State } - return new Scaffold( + return Scaffold( backgroundColor: Colors.transparent, body: GestureDetector( ///透明可以点击 @@ -152,42 +148,42 @@ class _BubbleTipWidgetState extends State width: widget.width, height: widget.height, margin: EdgeInsets.only(left: x, top: y), - child: new Stack( + child: Stack( children: [ ///绘制气泡背景 CustomPaint( key: paintKey, - size: new Size(widget.width!, widget.height!), + size: Size(widget.width!, widget.height!), painter: bubbleBuild.build()), Align( alignment: alignment, ///显示文本等 - child: new Container( + child: Container( margin: margin, width: widget.width, height: widget.height! - arrowHeight, alignment: Alignment.centerLeft, - child: new Row( + child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ - new Container( - margin: EdgeInsets.only(left: 20), + Container( + margin: const EdgeInsets.only(left: 20), height: widget.height, - child: new Icon( + child: Icon( Icons.notifications, size: widget.height! - 30, color: Theme.of(context).primaryColorDark, ), ), - new Expanded( - child: new Container( - margin: EdgeInsets.only(left: 5, right: 5), - child: new Text( + Expanded( + child: Container( + margin: const EdgeInsets.only(left: 5, right: 5), + child: Text( widget.text, - style: TextStyle(fontSize: 14, color: Colors.black), + style: const TextStyle(fontSize: 14, color: Colors.black), ), ), ) diff --git a/lib/widget/canvas_click_demo_page.dart b/lib/widget/canvas_click_demo_page.dart index 9a08b2f..dfe0087 100644 --- a/lib/widget/canvas_click_demo_page.dart +++ b/lib/widget/canvas_click_demo_page.dart @@ -4,6 +4,8 @@ import 'dart:math'; import 'package:flutter/material.dart'; class CanvasClickDemoPage extends StatefulWidget { + const CanvasClickDemoPage({super.key}); + @override _CanvasClickDemoPageState createState() => _CanvasClickDemoPageState(); } @@ -18,11 +20,11 @@ class _CanvasClickDemoPageState extends State @override void initState() { - timer = Timer.periodic(Duration(milliseconds: 800), (_) { + timer = Timer.periodic(const Duration(milliseconds: 800), (_) { setState(() {}); }); - controller = new AnimationController( - vsync: this, duration: Duration(milliseconds: 100)); + controller = AnimationController( + vsync: this, duration: const Duration(milliseconds: 100)); animation = Tween(begin: 0.0, end: 0.0).animate(controller); super.initState(); } @@ -39,35 +41,33 @@ class _CanvasClickDemoPageState extends State var time = DateTime.now(); return Scaffold( appBar: AppBar( - title: new Text("CanvasClickDemoPage"), + title: const Text("CanvasClickDemoPage"), ), - body: Container( - child: Center( - child: DebounceButton( - onTap: () { - if (controller.isAnimating) { - animation = Tween(begin: 0.0, end: 0.0).animate(controller); - controller.stop(); - setState(() {}); - } else { - CurvedAnimation curvedAnimation = CurvedAnimation( - parent: controller, curve: Curves.bounceInOut); - animation = Tween(begin: -0.01 * pi, end: 0.01 * pi) - .animate(curvedAnimation); - controller.repeat(reverse: true); - } - }, - child: RotationTransition( - turns: animation as Animation, - child: SizedBox( - width: 300, - height: 300, - child: CustomPaint( - painter: ClockPainter( - hour: time.hour, - minute: time.minute, - second: time.second, - ), + body: Center( + child: DebounceButton( + onTap: () { + if (controller.isAnimating) { + animation = Tween(begin: 0.0, end: 0.0).animate(controller); + controller.stop(); + setState(() {}); + } else { + CurvedAnimation curvedAnimation = CurvedAnimation( + parent: controller, curve: Curves.bounceInOut); + animation = Tween(begin: -0.01 * pi, end: 0.01 * pi) + .animate(curvedAnimation); + controller.repeat(reverse: true); + } + }, + child: RotationTransition( + turns: animation as Animation, + child: SizedBox( + width: 300, + height: 300, + child: CustomPaint( + painter: ClockPainter( + hour: time.hour, + minute: time.minute, + second: time.second, ), ), ), @@ -154,70 +154,70 @@ class ClockPainter extends CustomPainter { footLeftAngel; void init() { - clockCirclePaint = new Paint() + clockCirclePaint = Paint() ..isAntiAlias = true ..style = PaintingStyle.stroke ..color = edgeColor; - earPaint = new Paint() + earPaint = Paint() ..isAntiAlias = true ..style = PaintingStyle.fill ..color = earColor; - footPaint = new Paint() + footPaint = Paint() ..style = PaintingStyle.stroke ..strokeCap = StrokeCap.round ..strokeJoin = StrokeJoin.round ..color = footColor; - scalePaint = new Paint() + scalePaint = Paint() ..isAntiAlias = true ..style = PaintingStyle.stroke ..strokeCap = StrokeCap.round ..strokeJoin = StrokeJoin.round ..color = scaleColor; - headLinePaint = new Paint() + headLinePaint = Paint() ..isAntiAlias = true ..style = PaintingStyle.stroke ..color = headColor; - headCirclePaint = new Paint() + headCirclePaint = Paint() ..style = PaintingStyle.fill ..color = headColor; - centerCirclePaint = new Paint() + centerCirclePaint = Paint() ..style = PaintingStyle.fill ..color = centerPointColor; - hourHandPaint = new Paint() + hourHandPaint = Paint() ..isAntiAlias = true ..strokeJoin = StrokeJoin.round ..strokeCap = StrokeCap.round ..style = PaintingStyle.fill ..color = hourHandColor; - minHandPaint = new Paint() + minHandPaint = Paint() ..isAntiAlias = true ..strokeJoin = StrokeJoin.round ..strokeCap = StrokeCap.round ..color = minuteHandColor; - secondHandPaint = new Paint() + secondHandPaint = Paint() ..isAntiAlias = true ..strokeJoin = StrokeJoin.round ..strokeCap = StrokeCap.round ..color = secondHandColor; - earPath = new Path(); - earPath2 = new Path(); + earPath = Path(); + earPath2 = Path(); - footRightStartPointF = new Offset(0, 0); - footRightEndPointF = new Offset(0, 0); - footLeftStartPointF = new Offset(0, 0); - footLeftEndPointF = new Offset(0, 0); - earRightEndPointF = new Offset(0, 0); - earLeftEndPointF = new Offset(0, 0); + footRightStartPointF = const Offset(0, 0); + footRightEndPointF = const Offset(0, 0); + footLeftStartPointF = const Offset(0, 0); + footLeftEndPointF = const Offset(0, 0); + earRightEndPointF = const Offset(0, 0); + earLeftEndPointF = const Offset(0, 0); earRightAngel = 300 * pi / 180; earLeftAngel = 240 * pi / 180; @@ -369,7 +369,7 @@ class ClockPainter extends CustomPainter { } void drawEars(Canvas canvas, Size size) { - canvas.saveLayer(Offset.zero & size, new Paint()); + canvas.saveLayer(Offset.zero & size, Paint()); canvas.translate(centerX!, centerY!); canvas.rotate(-atan2(centerX!, centerY!)); canvas.translate(-centerX!, -centerY!); @@ -417,14 +417,14 @@ class DebounceButton extends StatefulWidget { final GestureTapCallback? onTap; final double radius; - DebounceButton({this.child, this.onTap, this.radius = 0}); + const DebounceButton({super.key, this.child, this.onTap, this.radius = 0}); @override _DebounceButtonState createState() => _DebounceButtonState(); } class _DebounceButtonState extends State { - Duration durationTime = Duration(milliseconds: 500); + Duration durationTime = const Duration(milliseconds: 500); Timer? timer; @override @@ -447,7 +447,7 @@ class _DebounceButtonState extends State { setState(() { if (timer == null) { widget.onTap?.call(); - timer = new Timer(durationTime, () { + timer = Timer(durationTime, () { timer = null; }); } diff --git a/lib/widget/card_3d_demo_page.dart b/lib/widget/card_3d_demo_page.dart index bc11b54..336fee0 100644 --- a/lib/widget/card_3d_demo_page.dart +++ b/lib/widget/card_3d_demo_page.dart @@ -5,7 +5,7 @@ import 'package:flutter/material.dart'; ///对应文章解析 https://juejin.cn/post/7124064789763981326 class Card3DDemoPage extends StatefulWidget { - const Card3DDemoPage({Key? key}) : super(key: key); + const Card3DDemoPage({super.key}); @override State createState() => _Card3DDemoPageState(); @@ -43,7 +43,7 @@ class _Card3DDemoPageState extends State { autoShow() { cancelShow(); - timer = Timer.periodic(Duration(milliseconds: 50), (timer) { + timer = Timer.periodic(const Duration(milliseconds: 50), (timer) { touchX = touchX + 0.05; touchX = touchX % (2 * pi); touchY = 0; @@ -61,10 +61,10 @@ class _Card3DDemoPageState extends State { showIndex = 1; } return Scaffold( - appBar: AppBar(title: Text("Card3DDemoPage")), + appBar: AppBar(title: const Text("Card3DDemoPage")), body: Container( alignment: Alignment.center, - decoration: BoxDecoration( + decoration: const BoxDecoration( gradient: LinearGradient( colors: [Colors.blueAccent, Colors.yellowAccent], begin: Alignment.topCenter, @@ -122,8 +122,8 @@ class _Card3DDemoPageState extends State { child: Container( width: cardWidth, height: cardHeight, - padding: EdgeInsets.all(20), - decoration: BoxDecoration( + padding: const EdgeInsets.all(20), + decoration: const BoxDecoration( image: DecorationImage( image: AssetImage("static/card_down.png")), boxShadow: [ @@ -142,8 +142,8 @@ class _Card3DDemoPageState extends State { child: Container( width: cardWidth, height: cardHeight, - padding: EdgeInsets.all(20), - decoration: BoxDecoration( + padding: const EdgeInsets.all(20), + decoration: const BoxDecoration( image: DecorationImage( image: AssetImage("static/card_up.png")), boxShadow: [ @@ -157,15 +157,15 @@ class _Card3DDemoPageState extends State { ), child: Column( children: [ - new Spacer(), - new Spacer(), - new Expanded( + const Spacer(), + const Spacer(), + Expanded( child: Text( "8888 8888 8888 8888", style: TextStyle( fontSize: 25, fontFamily: 'bglbt', - shadows: [ + shadows: const [ Shadow( color: Colors.black54, blurRadius: 2, @@ -174,12 +174,12 @@ class _Card3DDemoPageState extends State { foreground: Paint() ..style = PaintingStyle.stroke ..strokeWidth = 0.3 - ..shader = LinearGradient( + ..shader = const LinearGradient( begin: Alignment.centerLeft, end: Alignment.bottomRight, colors: [Colors.white, Colors.blueAccent, Colors.black54]) .createShader( - Rect.fromLTWH(0, 0, 1000, 100), + const Rect.fromLTWH(0, 0, 1000, 100), ), ), ), diff --git a/lib/widget/card_item_page.dart b/lib/widget/card_item_page.dart index 1742044..a7979df 100644 --- a/lib/widget/card_item_page.dart +++ b/lib/widget/card_item_page.dart @@ -1,49 +1,49 @@ import 'package:flutter/material.dart'; class CardItemPage extends StatelessWidget { + const CardItemPage({super.key}); + @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.blueAccent, appBar: AppBar( - title: new Text("CardItemPage"), - ), - body: Container( - child: Column(children: [ - renderImageNormal("static/gsy_cat.png"), - renderImageRatio(context, "static/gsy_cat.png"), - renderImageNormal("static/test.jpeg"), - renderImageRatio(context, "static/test.jpeg"), - ]), + title: const Text("CardItemPage"), ), + body: Column(children: [ + renderImageNormal("static/gsy_cat.png"), + renderImageRatio(context, "static/gsy_cat.png"), + renderImageNormal("static/test.jpeg"), + renderImageRatio(context, "static/test.jpeg"), + ]), ); } renderImageNormal(image) { return Card( - margin: EdgeInsets.all(5), + margin: const EdgeInsets.all(5), child: Container( - margin: EdgeInsets.only(right: 10), + margin: const EdgeInsets.only(right: 10), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ ClipRRect( - borderRadius: BorderRadius.only( + borderRadius: const BorderRadius.only( topLeft: Radius.circular(4.0), bottomLeft: Radius.circular(4.0), ), - child: new Image.asset( + child: Image.asset( image, fit: BoxFit.cover, width: 70, height: 70, ), ), - new SizedBox( + const SizedBox( width: 10, ), - new Expanded( - child: new Text( + const Expanded( + child: Text( 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', @@ -68,29 +68,29 @@ class CardItemPage extends StatelessWidget { //var data = MediaQueryData.fromWindow(WidgetsBinding.instance.window); return Card( - margin: EdgeInsets.all(5), + margin: const EdgeInsets.all(5), child: Container( - margin: EdgeInsets.only(right: 10), + margin: const EdgeInsets.only(right: 10), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ ClipRRect( - borderRadius: BorderRadius.only( + borderRadius: const BorderRadius.only( topLeft: Radius.circular(4.0), bottomLeft: Radius.circular(4.0), ), - child: new Image.asset( + child: Image.asset( image, fit: BoxFit.cover, height: itemHeight, width: itemHeight, ), ), - new SizedBox( + const SizedBox( width: 10, ), - new Expanded( - child: new Text( + Expanded( + child: Text( 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF' 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF', diff --git a/lib/widget/card_perspective_demo_page.dart b/lib/widget/card_perspective_demo_page.dart index 1709222..39a13a7 100644 --- a/lib/widget/card_perspective_demo_page.dart +++ b/lib/widget/card_perspective_demo_page.dart @@ -2,7 +2,7 @@ import 'package:flutter/material.dart'; ///对应文章解析 https://juejin.cn/post/7124064789763981326 class CardPerspectiveDemoPage extends StatefulWidget { - const CardPerspectiveDemoPage({Key? key}) : super(key: key); + const CardPerspectiveDemoPage({super.key}); @override State createState() => @@ -20,10 +20,10 @@ class _CardPerspectiveDemoPageState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar(title: Text("CardPerspectiveDemoPage")), + appBar: AppBar(title: const Text("CardPerspectiveDemoPage")), body: Container( alignment: Alignment.center, - decoration: BoxDecoration( + decoration: const BoxDecoration( gradient: LinearGradient( colors: [Colors.blueAccent, Colors.yellowAccent], begin: Alignment.topCenter, @@ -61,15 +61,15 @@ class _CardPerspectiveDemoPageState extends State { child: Container( width: cardWidth, height: cardHeight, - padding: EdgeInsets.all(20), + padding: const EdgeInsets.all(20), decoration: BoxDecoration( color: Colors.blueGrey, borderRadius: BorderRadius.circular(20), - gradient: LinearGradient( + gradient: const LinearGradient( colors: [Colors.white, Colors.blueGrey], begin: Alignment.topCenter, end: Alignment.bottomCenter), - boxShadow: [ + boxShadow: const [ BoxShadow( color: Colors.black54, blurRadius: 25, @@ -92,7 +92,7 @@ class _CardPerspectiveDemoPageState extends State { fontSize: 80, fontFamily: 'Canterbury', fontWeight: FontWeight.w800, - shadows: [ + shadows: const [ Shadow( color: Colors.black54, blurRadius: 2, @@ -101,17 +101,17 @@ class _CardPerspectiveDemoPageState extends State { foreground: Paint() ..style = PaintingStyle.fill ..strokeWidth = 3 - ..shader = LinearGradient( + ..shader = const LinearGradient( begin: Alignment.bottomLeft, end: Alignment.topRight, colors: [Colors.yellow, Colors.black]) - .createShader(Rect.fromLTWH(0, 0, 200, 100)), + .createShader(const Rect.fromLTWH(0, 0, 200, 100)), ), ), ), - new Container( - margin: EdgeInsets.only(top: 10, bottom: 10), - child: new Text( + Container( + margin: const EdgeInsets.only(top: 10, bottom: 10), + child: const Text( "MIUI 13", style: TextStyle( color: Colors.blueAccent, @@ -120,10 +120,10 @@ class _CardPerspectiveDemoPageState extends State { fontFamily: "Agne"), ), ), - new Spacer(), - new Container( - margin: EdgeInsets.only(bottom: 10), - child: new Text( + const Spacer(), + Container( + margin: const EdgeInsets.only(bottom: 10), + child: const Text( "新版本优化应用", style: TextStyle( color: Colors.white, diff --git a/lib/widget/card_real_3d_demo_page.dart b/lib/widget/card_real_3d_demo_page.dart index 17af3ff..9f89c98 100644 --- a/lib/widget/card_real_3d_demo_page.dart +++ b/lib/widget/card_real_3d_demo_page.dart @@ -4,7 +4,7 @@ import 'package:flutter/material.dart'; import 'package:zflutter/zflutter.dart'; class CardReal3DDemoPage extends StatefulWidget { - const CardReal3DDemoPage({Key? key}) : super(key: key); + const CardReal3DDemoPage({super.key}); @override State createState() => _CardReal3DDemoPageState(); @@ -41,13 +41,13 @@ class _CardReal3DDemoPageState extends State { Widget build(BuildContext context) { double width = 279; double height = 194; - final double screenRadius = 15; - final double border = 4; + const double screenRadius = 15; + const double border = 4; return Scaffold( - appBar: AppBar(title: Text("CardReal3DDemoPage")), + appBar: AppBar(title: const Text("CardReal3DDemoPage")), body: Container( - decoration: BoxDecoration( + decoration: const BoxDecoration( gradient: LinearGradient( colors: [Colors.blueAccent, Colors.yellowAccent], begin: Alignment.topCenter, @@ -65,7 +65,7 @@ class _CardReal3DDemoPageState extends State { sortMode: SortMode.stack, children: [ ZPositioned( - translate: ZVector(0, 0, -border / 2), + translate: const ZVector(0, 0, -border / 2), child: ZRoundedRect( width: width, height: height, @@ -80,30 +80,28 @@ class _CardReal3DDemoPageState extends State { height: height, child: ClipRRect( borderRadius: BorderRadius.circular(screenRadius), - child: Container( - child: Stack( - children: [ - SizedBox.fromSize( - size: Size(width, height), - child: Image.asset( - "static/card_down_2.png")), - Transform( - transform: Matrix4.identity()..rotateY(pi), - alignment: FractionalOffset.center, - child: Align( - alignment: Alignment(0.5, -0.07), - child: new Text( - "G S Y", - style: TextStyle( - fontSize: 23, - fontFamily: "bglbt", - fontStyle: FontStyle.italic, - fontWeight: FontWeight.bold), - ), + child: Stack( + children: [ + SizedBox.fromSize( + size: Size(width, height), + child: Image.asset( + "static/card_down_2.png")), + Transform( + transform: Matrix4.identity()..rotateY(pi), + alignment: FractionalOffset.center, + child: const Align( + alignment: Alignment(0.5, -0.07), + child: Text( + "G S Y", + style: TextStyle( + fontSize: 23, + fontFamily: "bglbt", + fontStyle: FontStyle.italic, + fontWeight: FontWeight.bold), ), - ) - ], - ), + ), + ) + ], ), ), ), @@ -139,7 +137,7 @@ class _CardReal3DDemoPageState extends State { stroke: 1, closed: false, backfaceColor: Colors.black54, - front: ZVector.only(z: 100), + front: const ZVector.only(z: 100), color: Colors.grey.withAlpha(200), ), ), @@ -150,12 +148,12 @@ class _CardReal3DDemoPageState extends State { stroke: 2, closed: false, backfaceColor: Colors.black54, - front: ZVector.only(z: 100), + front: const ZVector.only(z: 100), color: Colors.white.withAlpha(200), ), ), ZPositioned( - rotate: ZVector(0, 0, tau / 2), + rotate: const ZVector(0, 0, tau / 2), child: ZShape( visible: false, path: [...listNum(width, height, 2)], @@ -166,7 +164,7 @@ class _CardReal3DDemoPageState extends State { ), ), ZPositioned( - rotate: ZVector(0, 0, tau / 2), + rotate: const ZVector(0, 0, tau / 2), child: ZShape( visible: false, path: [...listNum(width, height, 1)], @@ -174,7 +172,7 @@ class _CardReal3DDemoPageState extends State { stroke: 2, closed: false, backfaceColor: Colors.black54, - front: ZVector.only(z: 100), + front: const ZVector.only(z: 100), color: Colors.white.withAlpha(200), ), ), diff --git a/lib/widget/chat_list_scroll_demo_page.dart b/lib/widget/chat_list_scroll_demo_page.dart index 7035760..46642de 100644 --- a/lib/widget/chat_list_scroll_demo_page.dart +++ b/lib/widget/chat_list_scroll_demo_page.dart @@ -2,7 +2,7 @@ import 'package:flutter/material.dart'; ///聊天列表,添加旧数据和新数据的时候不会导致列表跳动,首尾添加数据不会抖动 class ChatListScrollDemoPage extends StatefulWidget { - const ChatListScrollDemoPage({Key? key}) : super(key: key); + const ChatListScrollDemoPage({super.key}); @override _ChatListScrollDemoPageState createState() => _ChatListScrollDemoPageState(); @@ -10,9 +10,9 @@ class ChatListScrollDemoPage extends StatefulWidget { class _ChatListScrollDemoPageState extends State { List loadMoreData = [ - new ItemData(txt: "aaa11", type: "Right"), - new ItemData(txt: "aaa22", type: "Right"), - new ItemData(txt: "aaa33", type: "Right") + ItemData(txt: "aaa11", type: "Right"), + ItemData(txt: "aaa22", type: "Right"), + ItemData(txt: "aaa33", type: "Right") ]; List newData = []; @@ -26,10 +26,10 @@ class _ChatListScrollDemoPageState extends State { borderRadius: BorderRadius.circular(4), color: Colors.red, ), - margin: EdgeInsets.only(left: 50, right: 10, top: 5, bottom: 5), - padding: EdgeInsets.all(10), + margin: const EdgeInsets.only(left: 50, right: 10, top: 5, bottom: 5), + padding: const EdgeInsets.all(10), alignment: Alignment.centerRight, - child: new Text( + child: Text( data.txt, maxLines: 10, ), @@ -43,10 +43,10 @@ class _ChatListScrollDemoPageState extends State { borderRadius: BorderRadius.circular(4), color: Colors.green, ), - margin: EdgeInsets.only(right: 50, left: 10, top: 5, bottom: 5), - padding: EdgeInsets.all(10), + margin: const EdgeInsets.only(right: 50, left: 10, top: 5, bottom: 5), + padding: const EdgeInsets.all(10), alignment: Alignment.centerLeft, - child: new Text( + child: Text( data.txt, maxLines: 10, ), @@ -61,19 +61,19 @@ class _ChatListScrollDemoPageState extends State { newData.add( ItemData(txt: "#### new Send ${newData.length}", type: "Right")); setState(() {}); - Future.delayed(Duration(milliseconds: 1000), () { + Future.delayed(const Duration(milliseconds: 1000), () { scroller.jumpTo(scroller.position.minScrollExtent); }); }, - child: Text( + child: const Text( "Send", style: TextStyle(color: Colors.yellow), ), ), appBar: AppBar( - title: new Text("ControllerDemoPage"), + title: const Text("ControllerDemoPage"), actions: [ - new TextButton.icon( + TextButton.icon( onPressed: () { for (int i = 0; i < 20; i++) { loadMoreData.add(ItemData( @@ -81,15 +81,15 @@ class _ChatListScrollDemoPageState extends State { } setState(() {}); }, - icon: Icon( + icon: const Icon( Icons.add, color: Colors.red, ), - label: Text( + label: const Text( "add old", style: TextStyle(color: Colors.red), )), - new TextButton.icon( + TextButton.icon( onPressed: () { for (int i = 0; i < 20; i++) { newData.add( @@ -97,11 +97,11 @@ class _ChatListScrollDemoPageState extends State { } setState(() {}); }, - icon: Icon( + icon: const Icon( Icons.add, color: Colors.yellow, ), - label: Text( + label: const Text( "add new", style: TextStyle(color: Colors.yellow), )), @@ -117,10 +117,11 @@ class _ChatListScrollDemoPageState extends State { delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { var item = newData[index]; - if (item.type == "Right") + if (item.type == "Right") { return renderRightItem(item); - else + } else { return renderLeftItem(item); + } }, childCount: newData.length, ), @@ -133,10 +134,11 @@ class _ChatListScrollDemoPageState extends State { delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { var item = loadMoreData[index]; - if (item.type == "Right") + if (item.type == "Right") { return renderRightItem(item); - else + } else { return renderLeftItem(item); + } }, childCount: loadMoreData.length, ), diff --git a/lib/widget/chat_list_scroll_demo_page_2.dart b/lib/widget/chat_list_scroll_demo_page_2.dart index b6f6dfc..1ba61e2 100644 --- a/lib/widget/chat_list_scroll_demo_page_2.dart +++ b/lib/widget/chat_list_scroll_demo_page_2.dart @@ -3,7 +3,7 @@ import 'dart:math' as math; ///聊天列表,添加旧数据和新数据的时候不会导致列表跳动,首尾添加数据不会抖动 class ChatListScrollDemoPage2 extends StatefulWidget { - const ChatListScrollDemoPage2({Key? key}) : super(key: key); + const ChatListScrollDemoPage2({super.key}); @override _ChatListScrollDemoPageState2 createState() => @@ -14,9 +14,9 @@ class _ChatListScrollDemoPageState2 extends State { final random = math.Random(10); List newData = [ - new ItemData(txt: "*********init 1*********", type: "Left", size: 60), - new ItemData(txt: "*********init 2*********", type: "Left", size: 70), - new ItemData(txt: "*********init 3*********", type: "Left", size: 100) + ItemData(txt: "*********init 1*********", type: "Left", size: 60), + ItemData(txt: "*********init 2*********", type: "Left", size: 70), + ItemData(txt: "*********init 3*********", type: "Left", size: 100) ]; List loadMoreData = []; @@ -31,10 +31,10 @@ class _ChatListScrollDemoPageState2 extends State { borderRadius: BorderRadius.circular(4), color: Colors.red, ), - margin: EdgeInsets.only(left: 50, right: 10, top: 5, bottom: 5), - padding: EdgeInsets.all(10), + margin: const EdgeInsets.only(left: 50, right: 10, top: 5, bottom: 5), + padding: const EdgeInsets.all(10), alignment: Alignment.centerRight, - child: new Text( + child: Text( data.txt, maxLines: 10, ), @@ -48,17 +48,17 @@ class _ChatListScrollDemoPageState2 extends State { borderRadius: BorderRadius.circular(4), color: Colors.green, ), - margin: EdgeInsets.only(right: 50, left: 10, top: 5, bottom: 5), - padding: EdgeInsets.all(10), + margin: const EdgeInsets.only(right: 50, left: 10, top: 5, bottom: 5), + padding: const EdgeInsets.all(10), alignment: Alignment.centerLeft, - child: new Text( + child: Text( data.txt, maxLines: 10, ), ); } - ScrollPhysics _physics = BouncingScrollPhysics(); + final ScrollPhysics _physics = const BouncingScrollPhysics(); @override Widget build(BuildContext context) { @@ -70,19 +70,19 @@ class _ChatListScrollDemoPageState2 extends State { type: "Right", size: random.nextInt(60))); setState(() {}); - Future.delayed(Duration(milliseconds: 1000), () { + Future.delayed(const Duration(milliseconds: 1000), () { scroller.jumpTo(scroller.position.maxScrollExtent); }); }, - child: Text( + child: const Text( "Send", style: TextStyle(color: Colors.yellow), ), ), appBar: AppBar( - title: new Text("ControllerDemoPage"), + title: const Text("ControllerDemoPage"), actions: [ - new TextButton.icon( + TextButton.icon( onPressed: () { final random = math.Random(); int randomInt = random.nextInt(10); @@ -102,15 +102,15 @@ class _ChatListScrollDemoPageState2 extends State { } setState(() {}); }, - icon: Icon( + icon: const Icon( Icons.add, color: Colors.red, ), - label: Text( + label: const Text( "add old", style: TextStyle(color: Colors.red), )), - new TextButton.icon( + TextButton.icon( onPressed: () { final random = math.Random(); int randomInt = random.nextInt(10); @@ -130,13 +130,13 @@ class _ChatListScrollDemoPageState2 extends State { } setState(() {}); if (extentAfter == 0) { - ScaffoldMessenger.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( content: Text("你目前位于最底部,自动跳转新消息item"), duration: Duration(milliseconds: 1000), )); - Future.delayed(Duration(milliseconds: 200), () { + Future.delayed(const Duration(milliseconds: 200), () { scroller.jumpTo(scroller.position.maxScrollExtent); - Future.delayed(Duration(milliseconds: 400), () { + Future.delayed(const Duration(milliseconds: 400), () { scroller.jumpTo(scroller.position.maxScrollExtent); }); }); @@ -146,9 +146,9 @@ class _ChatListScrollDemoPageState2 extends State { onTap: () { scroller .jumpTo(scroller.position.maxScrollExtent * 0.7); - Future.delayed(Duration(milliseconds: 400), () { + Future.delayed(const Duration(milliseconds: 400), () { scroller.animateTo(scroller.position.maxScrollExtent, - duration: Duration(milliseconds: 500), + duration: const Duration(milliseconds: 500), curve: Curves.linear); }); }, @@ -157,18 +157,18 @@ class _ChatListScrollDemoPageState2 extends State { width: 200, color: Colors.blueAccent, alignment: Alignment.centerLeft, - child: Text("点击我自动跳转新消息item"), + child: const Text("点击我自动跳转新消息item"), ), ), - duration: Duration(milliseconds: 1000), + duration: const Duration(milliseconds: 1000), )); } }, - icon: Icon( + icon: const Icon( Icons.add, color: Colors.yellow, ), - label: Text( + label: const Text( "add new", style: TextStyle(color: Colors.yellow), )), @@ -239,10 +239,11 @@ class _ChatListScrollDemoPageState2 extends State { delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { var item = loadMoreData[index]; - if (item.type == "Right") + if (item.type == "Right") { return renderRightItem(item, random.nextInt(60).toDouble()); - else + } else { return renderLeftItem(item, random.nextInt(60).toDouble()); + } }, childCount: loadMoreData.length, ), @@ -255,10 +256,11 @@ class _ChatListScrollDemoPageState2 extends State { delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { var item = newData[index]; - if (item.type == "Right") + if (item.type == "Right") { return renderRightItem(item, item.size.toDouble()); - else + } else { return renderLeftItem(item, item.size.toDouble()); + } }, childCount: newData.length, ), diff --git a/lib/widget/clip_demo_page.dart b/lib/widget/clip_demo_page.dart index 03b0ae3..c02ccd5 100644 --- a/lib/widget/clip_demo_page.dart +++ b/lib/widget/clip_demo_page.dart @@ -2,24 +2,26 @@ import 'package:flutter/material.dart'; /// 圆角效果处理实现 class ClipDemoPage extends StatelessWidget { + const ClipDemoPage({super.key}); + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("ClipDemoPage"), + title: const Text("ClipDemoPage"), ), - body: new Container( + body: Container( alignment: Alignment.center, - margin: EdgeInsets.all(10), - child: new Column( + margin: const EdgeInsets.all(10), + child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ - new Text("BoxDecoration 圆角"), - new Container( + const Text("BoxDecoration 圆角"), + Container( width: 100, height: 100, - decoration: BoxDecoration( + decoration: const BoxDecoration( color: Colors.red, image: DecorationImage( fit: BoxFit.cover, @@ -27,30 +29,30 @@ class ClipDemoPage extends StatelessWidget { ), borderRadius: BorderRadius.all(Radius.circular(5.0))), ), - new SizedBox( + const SizedBox( height: 10, ), - new Text("BoxDecoration 圆角对 child"), - new Container( + const Text("BoxDecoration 圆角对 child"), + Container( width: 100, height: 100, - decoration: BoxDecoration( + decoration: const BoxDecoration( color: Colors.red, borderRadius: BorderRadius.all(Radius.circular(5.0))), - child: new Image.asset( + child: Image.asset( "static/gsy_cat.png", fit: BoxFit.cover, width: 100, height: 100, ), ), - new SizedBox( + const SizedBox( height: 10, ), - new Text("ClipRRect 圆角对 child"), - new ClipRRect( - borderRadius: BorderRadius.all(Radius.circular(5.0)), - child: new Image.asset( + const Text("ClipRRect 圆角对 child"), + ClipRRect( + borderRadius: const BorderRadius.all(Radius.circular(5.0)), + child: Image.asset( "static/gsy_cat.png", fit: BoxFit.cover, width: 100, diff --git a/lib/widget/cloud/cloud_demo_page.dart b/lib/widget/cloud/cloud_demo_page.dart index d27a9ae..cb04af4 100644 --- a/lib/widget/cloud/cloud_demo_page.dart +++ b/lib/widget/cloud/cloud_demo_page.dart @@ -5,6 +5,8 @@ import 'cloud_widget.dart'; ///云词图 class CloudDemoPage extends StatefulWidget { + const CloudDemoPage({super.key}); + @override _CloudDemoPageState createState() => _CloudDemoPageState(); } @@ -60,18 +62,18 @@ class _CloudDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("CloudDemoPage"), + title: const Text("CloudDemoPage"), ), - body: new Center( - child: Container( + body: Center( + child: SizedBox( width: MediaQuery.sizeOf(context).width, height: MediaQuery.sizeOf(context).width, ///利用 FittedBox 约束 child - child: new FittedBox( + child: FittedBox( /// Cloud 布局 child: Container( - padding: EdgeInsets.symmetric(vertical: 10, horizontal: 6), + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 6), color: Colors.brown, ///布局 @@ -86,7 +88,7 @@ class _CloudDemoPageState extends State { quarterTurns: item.rotate ? 1 : 0, child: Text( item.text, - style: new TextStyle( + style: TextStyle( fontSize: item.size, color: item.color, ), diff --git a/lib/widget/cloud/cloud_render.dart b/lib/widget/cloud/cloud_render.dart index 6fa692d..ddde117 100644 --- a/lib/widget/cloud/cloud_render.dart +++ b/lib/widget/cloud/cloud_render.dart @@ -18,7 +18,7 @@ class RenderCloudWidget extends RenderBox } ///圆周 - double _mathPi = math.pi * 2; + final double _mathPi = math.pi * 2; ///是否需要裁剪 bool _needClip = false; @@ -69,8 +69,9 @@ class RenderCloudWidget extends RenderBox ///设置为我们的数据 @override void setupParentData(RenderBox child) { - if (child.parentData is! RenderCloudParentData) + if (child.parentData is! RenderCloudParentData) { child.parentData = RenderCloudParentData(); + } } @override diff --git a/lib/widget/cloud/cloud_widget.dart b/lib/widget/cloud/cloud_widget.dart index ae872b9..efe16fa 100644 --- a/lib/widget/cloud/cloud_widget.dart +++ b/lib/widget/cloud/cloud_widget.dart @@ -6,12 +6,12 @@ class CloudWidget extends MultiChildRenderObjectWidget { final Clip overflow; final double ratio; - CloudWidget({ - Key? key, + const CloudWidget({ + super.key, this.ratio = 1, this.overflow = Clip.none, - List children = const [], - }) : super(key: key, children: children); + super.children, + }); @override RenderObject createRenderObject(BuildContext context) { diff --git a/lib/widget/color_progress_demo_page.dart b/lib/widget/color_progress_demo_page.dart index b251f11..df48eb8 100644 --- a/lib/widget/color_progress_demo_page.dart +++ b/lib/widget/color_progress_demo_page.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; class ColorProgressDemoPage extends StatefulWidget { + const ColorProgressDemoPage({super.key}); + @override _ColorProgressDemoPageState createState() => _ColorProgressDemoPageState(); } @@ -10,14 +12,14 @@ class _ColorProgressDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("ColorProgressDemoPage"), + title: const Text("ColorProgressDemoPage"), ), backgroundColor: Colors.grey, body: Center( child: Container( color: Colors.grey, alignment: Alignment.center, - margin: EdgeInsets.symmetric(horizontal: 50), + margin: const EdgeInsets.symmetric(horizontal: 50), child: Column( mainAxisSize: MainAxisSize.min, children: [ @@ -27,7 +29,7 @@ class _ColorProgressDemoPageState extends State { bgBorder: bgBorder1, value: 0.5, ), - SizedBox( + const SizedBox( height: 10, ), ColorProgress( @@ -36,7 +38,7 @@ class _ColorProgressDemoPageState extends State { bgBorder: bgBorder2, value: 0.3, ), - SizedBox( + const SizedBox( height: 10, ), ColorProgress( @@ -45,7 +47,7 @@ class _ColorProgressDemoPageState extends State { bgBorder: bgBorder3, value: 1, ), - SizedBox( + const SizedBox( height: 10, ), ProgressPainterAnim( @@ -54,7 +56,7 @@ class _ColorProgressDemoPageState extends State { bgBorder: bgBorder1, value: 0.8, ), - SizedBox( + const SizedBox( height: 10, ), ProgressPainterAnim( @@ -63,7 +65,7 @@ class _ColorProgressDemoPageState extends State { bgBorder: bgBorder2, value: 0.4, ), - SizedBox( + const SizedBox( height: 10, ), ProgressPainterAnim( @@ -86,8 +88,8 @@ class ColorProgress extends StatefulWidget { final Border bgBorder; final double value; - ColorProgress( - {required this.colorList, + const ColorProgress( + {super.key, required this.colorList, required this.backgroundColor, required this.value, required this.bgBorder}); @@ -101,25 +103,25 @@ class _ColorProgressState extends State { List renderColorList() { List widgetList = []; - widget.colorList.forEach((element) { + for (var element in widget.colorList) { widgetList.add( Container( decoration: BoxDecoration( gradient: element, - borderRadius: BorderRadius.only( + borderRadius: const BorderRadius.only( topRight: Radius.circular(8), bottomRight: Radius.circular(8)), ), child: Container(), ), ); - }); + } return widgetList; } @override void initState() { super.initState(); - Future.delayed(Duration(seconds: 0), () { + Future.delayed(const Duration(seconds: 0), () { setState(() { _value = widget.value; }); @@ -128,9 +130,9 @@ class _ColorProgressState extends State { @override Widget build(BuildContext context) { - var borderRadius = BorderRadius.all(Radius.circular(8)); + var borderRadius = const BorderRadius.all(Radius.circular(8)); return ClipRRect( - borderRadius: BorderRadius.all(Radius.circular(8)), + borderRadius: const BorderRadius.all(Radius.circular(8)), child: Container( decoration: BoxDecoration( border: widget.bgBorder, @@ -152,19 +154,15 @@ class _ColorProgressState extends State { minHeight: 10, maxHeight: 10, alignment: Alignment.centerLeft, - child: Container( - child: AnimatedContainer( - // Use the properties stored in the State class. - width: constraints.maxWidth * _value, - duration: Duration(seconds: 2), - curve: Curves.fastOutSlowIn, - child: Container( - child: Stack( - clipBehavior: Clip.none, - alignment: Alignment.center, - children: renderColorList(), - ), - ), + child: AnimatedContainer( + // Use the properties stored in the State class. + width: constraints.maxWidth * _value, + duration: const Duration(seconds: 2), + curve: Curves.fastOutSlowIn, + child: Stack( + clipBehavior: Clip.none, + alignment: Alignment.center, + children: renderColorList(), ), ), ), @@ -180,7 +178,7 @@ class _ColorProgressState extends State { } List colorList1 = [ - LinearGradient( + const LinearGradient( begin: Alignment(0.52576, 0.80444), end: Alignment(0.52576, 0.20356), stops: [ @@ -192,7 +190,7 @@ List colorList1 = [ Color.fromARGB(255, 255, 216, 152), ], ), - LinearGradient( + const LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, stops: [ @@ -210,7 +208,7 @@ List colorList1 = [ Color.fromARGB(255, 133, 101, 30), ], ), - LinearGradient( + const LinearGradient( begin: Alignment(1, 0.5), end: Alignment(0.5857, 0.5), stops: [ @@ -225,7 +223,7 @@ List colorList1 = [ ]; List colorList2 = [ - LinearGradient( + const LinearGradient( begin: Alignment(0.52576, 0.80444), end: Alignment(0.52576, 0.20356), stops: [ @@ -237,7 +235,7 @@ List colorList2 = [ Color.fromARGB(255, 255, 216, 152), ], ), - LinearGradient( + const LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, stops: [ @@ -255,7 +253,7 @@ List colorList2 = [ Color.fromARGB(255, 200, 28, 3), ], ), - LinearGradient( + const LinearGradient( begin: Alignment(1, 0.5), end: Alignment(0.5857, 0.5), stops: [ @@ -270,7 +268,7 @@ List colorList2 = [ ]; List colorList3 = [ - LinearGradient( + const LinearGradient( begin: Alignment(1, 0.5), end: Alignment(0, 0.5), stops: [ @@ -282,7 +280,7 @@ List colorList3 = [ Color.fromARGB(255, 255, 255, 255), ], ), - LinearGradient( + const LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, stops: [ @@ -300,7 +298,7 @@ List colorList3 = [ Color.fromARGB(0, 200, 28, 3), ], ), - LinearGradient( + const LinearGradient( begin: Alignment(1, 0.5), end: Alignment(0.5857, 0.5), stops: [ @@ -314,7 +312,7 @@ List colorList3 = [ ) ]; -var bgColor1 = LinearGradient( +var bgColor1 = const LinearGradient( begin: Alignment(0.99899, 0.5), end: Alignment(0, 0.5), stops: [ @@ -327,7 +325,7 @@ var bgColor1 = LinearGradient( ], ); -var bgColor2 = LinearGradient( +var bgColor2 = const LinearGradient( begin: Alignment(1, 0.5), end: Alignment(0, 0.5), stops: [ @@ -340,7 +338,7 @@ var bgColor2 = LinearGradient( ], ); -var bgColor3 = LinearGradient( +var bgColor3 = const LinearGradient( begin: Alignment(1, 0.5), end: Alignment(0, 0.5), stops: [ @@ -355,17 +353,17 @@ var bgColor3 = LinearGradient( var bgBorder1 = Border.all( width: 1, - color: Color.fromARGB(58, 92, 64, 18), + color: const Color.fromARGB(58, 92, 64, 18), ); var bgBorder2 = Border.all( width: 1, - color: Color.fromARGB(69, 255, 124, 124), + color: const Color.fromARGB(69, 255, 124, 124), ); var bgBorder3 = Border.all( width: 1, - color: Color.fromARGB(69, 113, 113, 113), + color: const Color.fromARGB(69, 113, 113, 113), ); class ProgressPainterAnim extends StatefulWidget { @@ -374,8 +372,8 @@ class ProgressPainterAnim extends StatefulWidget { final Border bgBorder; final double value; - ProgressPainterAnim( - {required this.colorList, + const ProgressPainterAnim( + {super.key, required this.colorList, required this.backgroundColor, required this.value, required this.bgBorder}); @@ -394,7 +392,7 @@ class _ProgressPainterAnimState extends State super.initState(); controller = AnimationController( vsync: this, - duration: Duration(seconds: 3), + duration: const Duration(seconds: 3), ); CurvedAnimation curvedAnimation = CurvedAnimation(parent: controller, curve: Curves.bounceInOut) @@ -413,7 +411,7 @@ class _ProgressPainterAnimState extends State @override Widget build(BuildContext context) { - return Container( + return SizedBox( height: 6, child: LayoutBuilder( builder: (context, size) { @@ -448,12 +446,12 @@ class ProgressPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { - Paint paint = new Paint(); + Paint paint = Paint(); var radiusOut = size.height / 2; var radiusInner = size.height / 2; - paint..shader = backgroundColor.createShader(Offset.zero & size); + paint.shader = backgroundColor.createShader(Offset.zero & size); canvas.drawRRect( RRect.fromLTRBR( 0, 0, size.width, size.height, Radius.circular(radiusOut)), @@ -463,9 +461,9 @@ class ProgressPainter extends CustomPainter { RRect.fromLTRBR( 0, 0, size.width, size.height, Radius.circular(radiusOut)), ); - colorList.forEach((element) { + for (var element in colorList) { paint - ..shader = element + .shader = element .createShader(Offset.zero & Size(size.width * value, size.height)); canvas.drawRRect( RRect.fromLTRBAndCorners(0, -5, size.width * value, size.height + 5, @@ -475,7 +473,7 @@ class ProgressPainter extends CustomPainter { bottomRight: Radius.circular(radiusInner)), paint, ); - }); + } bgBorder.paint(canvas, Offset.zero & size, borderRadius: BorderRadius.all(Radius.circular(radiusOut))); diff --git a/lib/widget/controller_demo_page.dart b/lib/widget/controller_demo_page.dart index 7d34863..0b643d9 100644 --- a/lib/widget/controller_demo_page.dart +++ b/lib/widget/controller_demo_page.dart @@ -1,4 +1,5 @@ import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; /// 在 Flutter 中有很多内置的 Controller @@ -7,9 +8,13 @@ import 'package:flutter/material.dart'; /// 比如 ListView 的 ScrollController /// 一般想对控件做 OOXX 的事情,先找个 Controller 就对了。 class ControllerDemoPage extends StatelessWidget { + const ControllerDemoPage({super.key}); + @override Widget build(BuildContext context) { - print("######### MyHomePage ${MediaQuery.of(context).size}"); + if (kDebugMode) { + print("######### MyHomePage ${MediaQuery.of(context).size}"); + } return Scaffold( appBar: AppBar(), body: Container( @@ -17,10 +22,10 @@ class ControllerDemoPage extends StatelessWidget { child: InkWell( onTap: () { Navigator.of(context).push(CupertinoPageRoute(builder: (context) { - return EditPage(); + return const EditPage(); })); }, - child: new Text( + child: const Text( "Click", style: TextStyle(fontSize: 50), ), @@ -32,23 +37,25 @@ class ControllerDemoPage extends StatelessWidget { class EditPage extends StatelessWidget { + const EditPage({super.key}); + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("ControllerDemoPage"), + title: const Text("ControllerDemoPage"), ), extendBody: true, body: Column( children: [ - new Spacer(), - new Container( - margin: EdgeInsets.all(10), - child: new Center( - child: new TextField(), + const Spacer(), + Container( + margin: const EdgeInsets.all(10), + child: const Center( + child: TextField(), ), ), - new Spacer(), + const Spacer(), ], ), ); diff --git a/lib/widget/custom_multi_render_demo_page.dart b/lib/widget/custom_multi_render_demo_page.dart index f2f3552..d3134d4 100644 --- a/lib/widget/custom_multi_render_demo_page.dart +++ b/lib/widget/custom_multi_render_demo_page.dart @@ -4,6 +4,8 @@ import 'package:flutter/material.dart'; ///通过 CustomMultiChildLayout 自定义控件 class CustomMultiRenderDemoPage extends StatefulWidget { + const CustomMultiRenderDemoPage({super.key}); + @override _CustomMultiRenderDemoPageState createState() => _CustomMultiRenderDemoPageState(); @@ -19,10 +21,10 @@ class _CustomMultiRenderDemoPageState extends State { double childSize = 66; return Scaffold( appBar: AppBar( - title: new Text("CustomMultiRenderDemoPage"), + title: const Text("CustomMultiRenderDemoPage"), ), - body: new Center( - child: new Container( + body: Center( + child: Container( color: Colors.greenAccent, width: MediaQuery.sizeOf(context).width, height: MediaQuery.sizeOf(context).width, @@ -41,7 +43,7 @@ class _CustomMultiRenderDemoPageState extends State { children: [ ///使用 LayoutId 指定 childId for (var item in customLayoutId) - new LayoutId(id: item, child: ContentItem(item, childSize)), + LayoutId(id: item, child: ContentItem(item, childSize)), ], ), ), @@ -56,7 +58,7 @@ class _CustomMultiRenderDemoPageState extends State { customLayoutId.add("${customLayoutId.length}"); }); }, - child: new Text( + child: const Text( "加", style: TextStyle(color: Colors.white), ), @@ -70,7 +72,7 @@ class _CustomMultiRenderDemoPageState extends State { } }); }, - child: new Text( + child: const Text( "减", style: TextStyle(color: Colors.white), ), @@ -117,7 +119,7 @@ class CircleLayoutDelegate extends MultiChildLayoutDelegate { final double centerY = childSize!.height / 2.0; - var result = new Offset(x - centerX, y - centerY); + var result = Offset(x - centerX, y - centerY); ///设置 child 位置 positionChild(item, result); @@ -135,7 +137,7 @@ class ContentItem extends StatelessWidget { final double childSize; - ContentItem(this.text, this.childSize); + const ContentItem(this.text, this.childSize, {super.key}); @override Widget build(BuildContext context) { @@ -144,9 +146,9 @@ class ContentItem extends StatelessWidget { borderRadius: BorderRadius.circular(childSize / 2.0), child: InkWell( radius: childSize / 2.0, - customBorder: CircleBorder(), + customBorder: const CircleBorder(), onTap: () {}, - child: Container( + child: SizedBox( width: childSize, height: childSize, child: Center( diff --git a/lib/widget/custom_pull/gsy_refresh_sliver.dart b/lib/widget/custom_pull/gsy_refresh_sliver.dart index a92feaa..b355728 100644 --- a/lib/widget/custom_pull/gsy_refresh_sliver.dart +++ b/lib/widget/custom_pull/gsy_refresh_sliver.dart @@ -12,12 +12,10 @@ import 'package:flutter/services.dart'; class _CupertinoSliverRefresh extends SingleChildRenderObjectWidget { const _CupertinoSliverRefresh({ - Key? key, this.refreshIndicatorLayoutExtent = 0.0, this.hasLayoutExtent = false, - Widget? child, - }) : assert(refreshIndicatorLayoutExtent >= 0.0), - super(key: key, child: child); + super.child, + }) : assert(refreshIndicatorLayoutExtent >= 0.0); // The amount of space the indicator should occupy in the sliver in a // resting state when in the refreshing mode. @@ -68,8 +66,9 @@ class _RenderCupertinoSliverRefresh extends RenderSliver double _refreshIndicatorExtent; set refreshIndicatorLayoutExtent(double value) { assert(value >= 0.0); - if (value == _refreshIndicatorExtent) + if (value == _refreshIndicatorExtent) { return; + } _refreshIndicatorExtent = value; markNeedsLayout(); } @@ -80,8 +79,9 @@ class _RenderCupertinoSliverRefresh extends RenderSliver bool get hasLayoutExtent => _hasLayoutExtent; bool _hasLayoutExtent; set hasLayoutExtent(bool value) { - if (value == _hasLayoutExtent) + if (value == _hasLayoutExtent) { return; + } _hasLayoutExtent = value; markNeedsLayout(); } @@ -278,7 +278,7 @@ class CupertinoSliverRefreshControl extends StatefulWidget { /// The [onRefresh] argument will be called when pulled far enough to trigger /// a refresh. const CupertinoSliverRefreshControl({ - Key? key, + super.key, this.refreshTriggerPullDistance = _defaultRefreshTriggerPullDistance, this.refreshIndicatorExtent = _defaultRefreshIndicatorExtent, this.builder = buildSimpleRefreshIndicator, @@ -289,8 +289,7 @@ class CupertinoSliverRefreshControl extends StatefulWidget { refreshTriggerPullDistance >= refreshIndicatorExtent, 'The refresh indicator cannot take more space in its final state ' 'than the amount initially created by overscrolling.' - ), - super(key: key); + ); /// The amount of overscroll the scrollable must be dragged to trigger a reload. /// diff --git a/lib/widget/custom_pull/refrsh_demo_page3.dart b/lib/widget/custom_pull/refrsh_demo_page3.dart index 5015fbc..be6f7a2 100644 --- a/lib/widget/custom_pull/refrsh_demo_page3.dart +++ b/lib/widget/custom_pull/refrsh_demo_page3.dart @@ -9,6 +9,8 @@ import 'package:gsy_flutter_demo/widget/custom_pull/gsy_refresh_sliver.dart'; ///比较粗略,没有做互斥等 ///详细使用还请查看 https://github.com/CarGuo/GSYGithubAppFlutter class RefreshDemoPage3 extends StatefulWidget { + const RefreshDemoPage3({super.key}); + @override _RefreshDemoPageState3 createState() => _RefreshDemoPageState3(); } @@ -23,10 +25,10 @@ class _RefreshDemoPageState3 extends State { List dataList = []; - final ScrollController _scrollController = new ScrollController(); + final ScrollController _scrollController = ScrollController(); Future onRefresh() async { - await Future.delayed(Duration(seconds: 2)); + await Future.delayed(const Duration(seconds: 2)); dataList.clear(); for (int i = 0; i < pageSize; i++) { dataList.add("refresh"); @@ -38,7 +40,7 @@ class _RefreshDemoPageState3 extends State { } Future loadMore() async { - await Future.delayed(Duration(seconds: 2)); + await Future.delayed(const Duration(seconds: 2)); for (int i = 0; i < pageSize; i++) { dataList.add("loadmore"); } @@ -53,9 +55,9 @@ class _RefreshDemoPageState3 extends State { super.didChangeDependencies(); ///直接触发下拉 - new Future.delayed(const Duration(milliseconds: 500), () { + Future.delayed(const Duration(milliseconds: 500), () { _scrollController.animateTo(-141, - duration: Duration(milliseconds: 600), curve: Curves.linear); + duration: const Duration(milliseconds: 600), curve: Curves.linear); return true; }); } @@ -70,71 +72,69 @@ class _RefreshDemoPageState3 extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("RefreshDemoPage"), + title: const Text("RefreshDemoPage"), ), - body: Container( - child: new NotificationListener( - onNotification: (ScrollNotification notification) { - ///通知 CupertinoSliverRefreshControl 当前的拖拽状态 - sliverRefreshKey.currentState! - .notifyScrollNotification(notification); - ///判断当前滑动位置是不是到达底部,触发加载更多回调 - if (notification is ScrollEndNotification) { - if (_scrollController.position.pixels > 0 && - _scrollController.position.pixels == - _scrollController.position.maxScrollExtent) { - loadMore(); - } - + body: NotificationListener( + onNotification: (ScrollNotification notification) { + ///通知 CupertinoSliverRefreshControl 当前的拖拽状态 + sliverRefreshKey.currentState! + .notifyScrollNotification(notification); + ///判断当前滑动位置是不是到达底部,触发加载更多回调 + if (notification is ScrollEndNotification) { + if (_scrollController.position.pixels > 0 && + _scrollController.position.pixels == + _scrollController.position.maxScrollExtent) { + loadMore(); } - return false; - }, - child: CustomScrollView( - controller: _scrollController, - - ///回弹效果 - physics: const BouncingScrollPhysics( - parent: AlwaysScrollableScrollPhysics()), - slivers: [ - ///控制显示刷新的 CupertinoSliverRefreshControl - CupertinoSliverRefreshControl( - key: sliverRefreshKey, - refreshIndicatorExtent: 100, - refreshTriggerPullDistance: 140, - onRefresh: onRefresh, - builder: buildSimpleRefreshIndicator, - ), - ///列表区域 - SliverSafeArea( - sliver: SliverList( - ///代理显示 - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - if (index == dataList.length) { - return new Container( - margin: EdgeInsets.all(10), - child: Align( - child: CircularProgressIndicator(), - ), - ); - } - return Card( - child: new Container( - height: 60, - alignment: Alignment.centerLeft, - child: new Text("Item ${dataList[index]} $index"), + } + return false; + }, + child: CustomScrollView( + controller: _scrollController, + + ///回弹效果 + physics: const BouncingScrollPhysics( + parent: AlwaysScrollableScrollPhysics()), + slivers: [ + ///控制显示刷新的 CupertinoSliverRefreshControl + CupertinoSliverRefreshControl( + key: sliverRefreshKey, + refreshIndicatorExtent: 100, + refreshTriggerPullDistance: 140, + onRefresh: onRefresh, + builder: buildSimpleRefreshIndicator, + ), + + ///列表区域 + SliverSafeArea( + sliver: SliverList( + ///代理显示 + delegate: SliverChildBuilderDelegate( + (BuildContext context, int index) { + if (index == dataList.length) { + return Container( + margin: const EdgeInsets.all(10), + child: const Align( + child: CircularProgressIndicator(), ), ); - }, - childCount: (dataList.length >= pageSize) - ? dataList.length + 1 - : dataList.length, - ), + } + return Card( + child: Container( + height: 60, + alignment: Alignment.centerLeft, + child: Text("Item ${dataList[index]} $index"), + ), + ); + }, + childCount: (dataList.length >= pageSize) + ? dataList.length + 1 + : dataList.length, ), ), - ], - ), + ), + ], ), ), ); diff --git a/lib/widget/custom_shader_path_demo_page.dart b/lib/widget/custom_shader_path_demo_page.dart index ce54def..3ef3695 100644 --- a/lib/widget/custom_shader_path_demo_page.dart +++ b/lib/widget/custom_shader_path_demo_page.dart @@ -4,7 +4,7 @@ import 'dart:ui' as ui; import 'package:flutter/material.dart'; class CustomShaderPathDemoPage extends StatefulWidget { - const CustomShaderPathDemoPage({Key? key}) : super(key: key); + const CustomShaderPathDemoPage({super.key}); @override State createState() => @@ -13,10 +13,10 @@ class CustomShaderPathDemoPage extends StatefulWidget { class _CustomShaderPathDemoPageState extends State { Future _loadAssetImage() { - Completer completer = new Completer(); + Completer completer = Completer(); - AssetImage("static/gsy_cat.png") - .resolve(new ImageConfiguration()) + const AssetImage("static/gsy_cat.png") + .resolve(const ImageConfiguration()) .addListener( ImageStreamListener((ImageInfo image, bool synchronousCall) { ui.Image img; @@ -31,34 +31,32 @@ class _CustomShaderPathDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("CustomShaderPathDemoPage"), + title: const Text("CustomShaderPathDemoPage"), ), - body: new Container( - child: Center( - child: FutureBuilder( - future: _loadAssetImage(), - builder: (c, s) { - if (s.data == null) { - return Container(); - } - return new Container( - height: 200, - width: 200, - color: Colors.greenAccent, - child: CustomPaint( - ///直接使用值做动画 - foregroundPainter: _AnimationPainter(s.data!), - ), - ); - }, - ), + body: Center( + child: FutureBuilder( + future: _loadAssetImage(), + builder: (c, s) { + if (s.data == null) { + return Container(); + } + return Container( + height: 200, + width: 200, + color: Colors.greenAccent, + child: CustomPaint( + ///直接使用值做动画 + foregroundPainter: _AnimationPainter(s.data!), + ), + ); + }, ), )); } } class _AnimationPainter extends CustomPainter { - final Paint _paint = new Paint(); + final Paint _paint = Paint(); final ui.Image img; @@ -96,13 +94,15 @@ class _AnimationPainter extends CustomPainter { var b = path.getBounds(); canvas.save(); canvas.clipPath(path); - for (int i = step; i < b.width; i = i + step) + for (int i = step; i < b.width; i = i + step) { canvas.drawLine( Offset(b.left + i, b.top), Offset(b.left + i, b.bottom), Paint()); + } - for (int i = step; i < b.height; i = i + step) + for (int i = step; i < b.height; i = i + step) { canvas.drawLine( Offset(b.left, b.top + i), Offset(b.right, b.top + i), Paint()); + } canvas.restore(); } diff --git a/lib/widget/custom_sliver/custom_sliver.dart b/lib/widget/custom_sliver/custom_sliver.dart index a4bf54a..e68d8c5 100644 --- a/lib/widget/custom_sliver/custom_sliver.dart +++ b/lib/widget/custom_sliver/custom_sliver.dart @@ -5,14 +5,12 @@ import 'package:flutter/rendering.dart'; class _CustomSliver extends SingleChildRenderObjectWidget { const _CustomSliver({ - Key? key, this.containerLayoutExtent = 0.0, this.initLayoutExtent = 0.0, this.hasLayoutExtent = false, this.pinned = false, - Widget? child, - }) : assert(containerLayoutExtent >= 0.0), - super(key: key, child: child); + super.child, + }) : assert(containerLayoutExtent >= 0.0); final double initLayoutExtent; final double containerLayoutExtent; @@ -223,7 +221,7 @@ typedef ContainerBuilder = Widget Function( class CustomSliver extends StatefulWidget { const CustomSliver({ - Key? key, + super.key, this.triggerPullDistance = _defaultTriggerPullDistance, this.containerExtent = _defaultcontainerExtent, this.initLayoutExtent = 0, @@ -234,8 +232,7 @@ class CustomSliver extends StatefulWidget { assert( triggerPullDistance >= containerExtent, 'The container cannot take more space in its final state ' - 'than the amount initially created by overscrolling.'), - super(key: key); + 'than the amount initially created by overscrolling.'); final double triggerPullDistance; @@ -259,19 +256,18 @@ class CustomSliver extends StatefulWidget { const Curve opacityCurve = Interval(0.0, 1, curve: Curves.easeInOut); return Stack( children: [ - new Opacity( + Opacity( opacity: 1.0, - child: new Container(color: Colors.red), + child: Container(color: Colors.red), ), - new Opacity( + Opacity( opacity: opacityCurve.transform(min(pulledExtent / containerExtent, 1.0)), child: InkWell( onTap: () { - print("FFFF"); }, - child: new Container( - decoration: BoxDecoration( + child: Container( + decoration: const BoxDecoration( color: Colors.amber, image: DecorationImage( fit: BoxFit.cover, diff --git a/lib/widget/custom_sliver/scroll_header_demo_page.dart b/lib/widget/custom_sliver/scroll_header_demo_page.dart index 1816644..17d9cb4 100644 --- a/lib/widget/custom_sliver/scroll_header_demo_page.dart +++ b/lib/widget/custom_sliver/scroll_header_demo_page.dart @@ -2,13 +2,15 @@ import 'package:flutter/material.dart'; import 'custom_sliver.dart'; class ScrollHeaderDemoPage extends StatefulWidget { + const ScrollHeaderDemoPage({super.key}); + @override _ScrollHeaderDemoPageState createState() => _ScrollHeaderDemoPageState(); } class _ScrollHeaderDemoPageState extends State with SingleTickerProviderStateMixin { - GlobalKey globalKey = new GlobalKey(); + GlobalKey globalKey = GlobalKey(); final ScrollController controller = ScrollController(initialScrollOffset: -70); @@ -24,9 +26,9 @@ class _ScrollHeaderDemoPageState extends State return Scaffold( backgroundColor: Theme.of(context).primaryColorDark, appBar: AppBar( - title: new Text("ScrollHeaderDemoPage"), + title: const Text("ScrollHeaderDemoPage"), ), - body: new NotificationListener( + body: NotificationListener( onNotification: (ScrollNotification notification) { if (notification is ScrollUpdateNotification) { if (initLayoutExtent > 0) { @@ -60,7 +62,7 @@ class _ScrollHeaderDemoPageState extends State SliverPadding( padding: EdgeInsets.only(bottom: pinned ? initLayoutExtent : 0), sliver: SliverGrid( - gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 2, crossAxisSpacing: 2, @@ -71,10 +73,10 @@ class _ScrollHeaderDemoPageState extends State delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return Card( - child: new Container( + child: Container( height: 60, alignment: Alignment.centerLeft, - child: new Text("Item $index"), + child: Text("Item $index"), ), ); }, @@ -86,18 +88,18 @@ class _ScrollHeaderDemoPageState extends State ), ), persistentFooterButtons: [ - new ElevatedButton( + ElevatedButton( onPressed: () async { setState(() { pinned = !pinned; }); }, - child: new Text( + child: Text( pinned ? "pinned" : "scroll", - style: TextStyle(color: Colors.white), + style: const TextStyle(color: Colors.white), ), ), - new ElevatedButton( + ElevatedButton( onPressed: () async { setState(() { if (initLayoutExtent == 0) { @@ -108,12 +110,12 @@ class _ScrollHeaderDemoPageState extends State } }); }, - child: new Text( + child: Text( initLayoutExtent != 0 ? "minHeight" : "non Height", - style: TextStyle(color: Colors.white), + style: const TextStyle(color: Colors.white), ), ), - new ElevatedButton( + ElevatedButton( onPressed: () async { setState(() { if (showPullDistance > 150) { @@ -123,9 +125,9 @@ class _ScrollHeaderDemoPageState extends State } }); }, - child: new Text( + child: Text( showPullDistance > 150 ? "autoBack" : "non autoBack", - style: TextStyle(color: Colors.white), + style: const TextStyle(color: Colors.white), ), ), ], diff --git a/lib/widget/custom_viewport/custom_viewport.dart b/lib/widget/custom_viewport/custom_viewport.dart index a82e8ac..06afca6 100644 --- a/lib/widget/custom_viewport/custom_viewport.dart +++ b/lib/widget/custom_viewport/custom_viewport.dart @@ -1,4 +1,5 @@ import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; @@ -7,24 +8,16 @@ class CustomViewport extends Viewport { final List highestChildInPaintOrderClassList; CustomViewport({ - Key? key, - AxisDirection axisDirection = AxisDirection.down, - AxisDirection? crossAxisDirection, - double anchor = 0.0, - required ViewportOffset offset, - Key? center, - double? cacheExtent, - List slivers = const [], + super.key, + super.axisDirection, + super.crossAxisDirection, + super.anchor, + required super.offset, + super.center, + super.cacheExtent, + super.slivers, this.highestChildInPaintOrderClassList = const [], - }) : super( - key: key, - slivers: slivers, - axisDirection: axisDirection, - crossAxisDirection: crossAxisDirection, - anchor: anchor, - offset: offset, - center: center, - cacheExtent: cacheExtent); + }); @override RenderViewport createRenderObject(BuildContext context) { @@ -44,23 +37,13 @@ class _RenderExpandedViewport extends RenderViewport { final List highestChildInPaintOrderClassList; _RenderExpandedViewport({ - AxisDirection axisDirection = AxisDirection.down, - required AxisDirection crossAxisDirection, - required ViewportOffset offset, - double anchor = 0.0, - List? children, - RenderSliver? center, - double? cacheExtent, + super.axisDirection, + required super.crossAxisDirection, + required super.offset, + super.anchor, + super.cacheExtent, this.highestChildInPaintOrderClassList = const [], - }) : super( - axisDirection: axisDirection, - crossAxisDirection: crossAxisDirection, - offset: offset, - anchor: anchor, - children: children, - center: center, - cacheExtent: cacheExtent, - ); + }); @override Iterable get childrenInPaintOrder { @@ -84,16 +67,18 @@ class _RenderExpandedViewport extends RenderViewport { child = childAfter(child); } if (highestChildInPaintOrderClassList.isNotEmpty) { - highestChildInPaintOrderClassList.forEach((clazz) { + for (var clazz in highestChildInPaintOrderClassList) { try { final renderSliver = children.firstWhere((child) => child.runtimeType == clazz); children.remove(renderSliver); children.add(renderSliver); } catch (e) { - print(e); + if (kDebugMode) { + print(e); + } } - }); + } return children; } else { return children.reversed.toList(); diff --git a/lib/widget/custom_viewport/custom_viewport_page.dart b/lib/widget/custom_viewport/custom_viewport_page.dart index a1ad971..3b47bee 100644 --- a/lib/widget/custom_viewport/custom_viewport_page.dart +++ b/lib/widget/custom_viewport/custom_viewport_page.dart @@ -7,7 +7,7 @@ import 'package:gsy_flutter_demo/widget/custom_viewport/secondary_tab_bar.dart'; import 'package:gsy_flutter_demo/widget/custom_viewport/secondary_tab_bar_render_sliver.dart'; class CustomViewportPage extends StatelessWidget { - const CustomViewportPage({Key? key}) : super(key: key); + const CustomViewportPage({super.key}); @override Widget build(BuildContext context) { @@ -17,7 +17,7 @@ class CustomViewportPage extends StatelessWidget { viewportBuilder: (BuildContext context, ViewportOffset position) { return CustomViewport( offset: position, - highestChildInPaintOrderClassList: [ + highestChildInPaintOrderClassList: const [ FirstTabBarRenderSliver, SecondaryTabBarRenderSliver, ], diff --git a/lib/widget/custom_viewport/first_tab_bar.dart b/lib/widget/custom_viewport/first_tab_bar.dart index ab7fa3b..a49ae78 100644 --- a/lib/widget/custom_viewport/first_tab_bar.dart +++ b/lib/widget/custom_viewport/first_tab_bar.dart @@ -3,8 +3,8 @@ import 'package:gsy_flutter_demo/widget/custom_viewport/first_tab_bar_sliver_wid class FirstTabBar extends StatelessWidget { const FirstTabBar({ - Key? key, - }) : super(key: key); + super.key, + }); @override Widget build(BuildContext context) { @@ -17,7 +17,7 @@ class FirstTabBar extends StatelessWidget { return Container( height: 66, color: Colors.deepPurpleAccent, - child: Center( + child: const Center( child: Text('一级tab'), ), ); diff --git a/lib/widget/custom_viewport/first_tab_bar_sliver_widget.dart b/lib/widget/custom_viewport/first_tab_bar_sliver_widget.dart index 9c100fa..eb5ebe0 100644 --- a/lib/widget/custom_viewport/first_tab_bar_sliver_widget.dart +++ b/lib/widget/custom_viewport/first_tab_bar_sliver_widget.dart @@ -2,8 +2,7 @@ import 'package:flutter/material.dart'; import 'package:gsy_flutter_demo/widget/custom_viewport/first_tab_bar_render_sliver.dart'; class FirstTabBarSliverWidget extends SingleChildRenderObjectWidget { - const FirstTabBarSliverWidget({Widget? child, Key? key}) - : super(key: key, child: child); + const FirstTabBarSliverWidget({super.child, super.key}); @override RenderObject createRenderObject(BuildContext context) { diff --git a/lib/widget/custom_viewport/secondary_tab_bar.dart b/lib/widget/custom_viewport/secondary_tab_bar.dart index 7cd3cc4..7744c7e 100644 --- a/lib/widget/custom_viewport/secondary_tab_bar.dart +++ b/lib/widget/custom_viewport/secondary_tab_bar.dart @@ -3,8 +3,8 @@ import 'package:gsy_flutter_demo/widget/custom_viewport/secondary_tab_bar_sliver class SecondaryTabBar extends StatelessWidget { const SecondaryTabBar({ - Key? key, - }) : super(key: key); + super.key, + }); @override Widget build(BuildContext context) { @@ -17,7 +17,7 @@ class SecondaryTabBar extends StatelessWidget { return Container( height: 66, color: Colors.red.withOpacity(0.8), - child: Center(child: Text('二级tab')), + child: const Center(child: Text('二级tab')), ); } } diff --git a/lib/widget/custom_viewport/secondary_tab_bar_sliver_widget.dart b/lib/widget/custom_viewport/secondary_tab_bar_sliver_widget.dart index 5081483..9b22f34 100644 --- a/lib/widget/custom_viewport/secondary_tab_bar_sliver_widget.dart +++ b/lib/widget/custom_viewport/secondary_tab_bar_sliver_widget.dart @@ -3,8 +3,7 @@ import 'package:flutter/material.dart'; import 'secondary_tab_bar_render_sliver.dart'; class SecondaryTabBarSliverWidget extends SingleChildRenderObjectWidget { - const SecondaryTabBarSliverWidget({Widget? child, Key? key}) - : super(key: key, child: child); + const SecondaryTabBarSliverWidget({super.child, super.key}); @override RenderObject createRenderObject(BuildContext context) { diff --git a/lib/widget/dash_3d_demo_page.dart b/lib/widget/dash_3d_demo_page.dart index 5884afc..3d4f568 100644 --- a/lib/widget/dash_3d_demo_page.dart +++ b/lib/widget/dash_3d_demo_page.dart @@ -2,7 +2,7 @@ import 'package:flutter/material.dart'; import 'package:zflutter/zflutter.dart'; class Dash3dDemoPage extends StatefulWidget { - const Dash3dDemoPage({Key? key}) : super(key: key); + const Dash3dDemoPage({super.key}); @override State createState() => _Dash3dDemoPageState(); @@ -19,15 +19,16 @@ class _Dash3dDemoPageState extends State super.initState(); animationController = AnimationController( vsync: this, - duration: Duration(seconds: 10), + duration: const Duration(seconds: 10), ); update(); } update() { - Future.delayed(Duration(seconds: 2), () { - if (mounted) + Future.delayed(const Duration(seconds: 2), () { + if (mounted) { animationController.forward(from: 0).whenComplete(() => update()); + } }); } @@ -50,7 +51,7 @@ class _Dash3dDemoPageState extends State )); return Scaffold( appBar: AppBar( - title: Text("Dash3dDemoPage"), + title: const Text("Dash3dDemoPage"), ), body: Center( child: ZDragDetector(builder: (context, controller) { @@ -75,20 +76,20 @@ class _Dash3dDemoPageState extends State } } -final Color darkBlue = Color(0xff5CC0EF); +const Color darkBlue = Color(0xff5CC0EF); -final Color bodyColor = Color(0xffa0e6fe); +const Color bodyColor = Color(0xffa0e6fe); -final Color brown = Color(0xff967C40); +const Color brown = Color(0xff967C40); -final Color green = Color(0xff71d3c7); +const Color green = Color(0xff71d3c7); -final Color black = Color(0xff000000); +const Color black = Color(0xff000000); class Dash extends StatelessWidget { final double flight; - Dash({required this.flight}); + const Dash({super.key, required this.flight}); @override Widget build(BuildContext context) { @@ -101,40 +102,40 @@ class Dash extends StatelessWidget { fill: true, color: bodyColor, ), - ZPositioned(translate: ZVector.only(y: -20), child: hair()), + ZPositioned(translate: const ZVector.only(y: -20), child: hair()), ZPositioned( - translate: ZVector.only(x: 0, y: 12, z: -17), + translate: const ZVector.only(x: 0, y: 12, z: -17), child: ZShape( stroke: 2, fill: true, path: [ - ZMove.vector( + const ZMove.vector( ZVector.only(x: 0, y: 0, z: 0), ), ZArc.list([ - ZVector.only(x: 5, y: -10, z: -8), - ZVector.only(x: 8, y: -15, z: -10), + const ZVector.only(x: 5, y: -10, z: -8), + const ZVector.only(x: 8, y: -15, z: -10), ], null), ZArc.list([ - ZVector.only(x: 0, y: -25, z: -12), - ZVector.only(x: -8, y: -15, z: -10), + const ZVector.only(x: 0, y: -25, z: -12), + const ZVector.only(x: -8, y: -15, z: -10), ], null), ZArc.list([ - ZVector.only(x: -5, y: -10, z: -8), - ZVector.only(x: 0, y: -0, z: 0), + const ZVector.only(x: -5, y: -10, z: -8), + const ZVector.only(x: 0, y: -0, z: 0), ], null) ], color: darkBlue, ), ), ZPositioned( - translate: ZVector.only(x: -23, z: -2), + translate: const ZVector.only(x: -23, z: -2), rotate: ZVector.only(y: tau / 4 - tau / 40 - flight / 12, x: -tau / 12), child: wing(), ), ZPositioned( - translate: ZVector.only(x: 23, z: -2), + translate: const ZVector.only(x: 23, z: -2), rotate: ZVector.only(y: tau / 4 + tau / 40 + flight / 12, x: -tau / 12), child: wing(), @@ -143,34 +144,34 @@ class Dash extends StatelessWidget { sortMode: SortMode.stack, children: [ ZPositioned( - translate: ZVector.only(x: 0, y: 0, z: 2), + translate: const ZVector.only(x: 0, y: 0, z: 2), child: ZShape( stroke: 2, fill: true, path: [ - ZMove.vector( + const ZMove.vector( ZVector.only(x: 0, y: 0, z: 20), ), ZArc.list([ - ZVector.only(x: -30, y: 7, z: 15), - ZVector.only(x: 0, y: 15, z: 15), + const ZVector.only(x: -30, y: 7, z: 15), + const ZVector.only(x: 0, y: 15, z: 15), ], null), ZArc.list([ - ZVector.only(x: 30, y: 7, z: 15), - ZVector.only(x: 0, y: 0, z: 20), + const ZVector.only(x: 30, y: 7, z: 15), + const ZVector.only(x: 0, y: 0, z: 20), ], null) ], color: Colors.white, ), ), ZPositioned( - translate: ZVector.only(z: 20), + translate: const ZVector.only(z: 20), child: ZGroup(sortMode: SortMode.update, children: [ - eye(translate: ZVector.only(x: -7)), - eye(translate: ZVector.only(x: 7)), + eye(translate: const ZVector.only(x: -7)), + eye(translate: const ZVector.only(x: 7)), ZPositioned( - rotate: ZVector.only(x: -tau / 20), - translate: ZVector.only(y: 7), + rotate: const ZVector.only(x: -tau / 20), + translate: const ZVector.only(y: 7), child: ZCone( color: brown, length: 10, @@ -191,7 +192,7 @@ class Dash extends StatelessWidget { ZGroup hair() => ZGroup( children: [ ZPositioned( - translate: ZVector.only(y: -1, z: 0), + translate: const ZVector.only(y: -1, z: 0), child: ZEllipse( height: 6, width: 3, @@ -200,8 +201,8 @@ ZGroup hair() => ZGroup( ), ), ZPositioned( - translate: ZVector.only(y: 1, x: -2), - rotate: ZVector.only(z: -tau / 8), + translate: const ZVector.only(y: 1, x: -2), + rotate: const ZVector.only(z: -tau / 8), child: ZEllipse( height: 6, width: 3, @@ -210,8 +211,8 @@ ZGroup hair() => ZGroup( ), ), ZPositioned( - translate: ZVector.only(y: 1, x: 2), - rotate: ZVector.only(z: tau / 8), + translate: const ZVector.only(y: 1, x: 2), + rotate: const ZVector.only(z: tau / 8), child: ZEllipse( height: 6, width: 3, @@ -235,7 +236,7 @@ ZGroup eye({ZVector translate = ZVector.zero}) { ), ZPositioned( translate: translate, - scale: ZVector.all(1.2), + scale: const ZVector.all(1.2), child: ZEllipse( stroke: 2, fill: true, @@ -245,7 +246,7 @@ ZGroup eye({ZVector translate = ZVector.zero}) { ), ), ZPositioned( - translate: translate + ZVector.only(x: 0, y: 0, z: 0.1), + translate: translate + const ZVector.only(x: 0, y: 0, z: 0.1), child: ZEllipse( stroke: 2, fill: true, @@ -255,7 +256,7 @@ ZGroup eye({ZVector translate = ZVector.zero}) { ), ), ZPositioned( - translate: translate + ZVector.only(x: 2, y: -2, z: 1), + translate: translate + const ZVector.only(x: 2, y: -2, z: 1), child: ZCircle( stroke: 1, fill: true, @@ -269,7 +270,7 @@ ZGroup eye({ZVector translate = ZVector.zero}) { ZGroup wing() => ZGroup( children: [ ZPositioned( - scale: ZVector.all(1.2), + scale: const ZVector.all(1.2), child: ZEllipse( stroke: 4, fill: true, diff --git a/lib/widget/demo_draggable_sheet_stick_page.dart b/lib/widget/demo_draggable_sheet_stick_page.dart index 347de0b..7e46d38 100644 --- a/lib/widget/demo_draggable_sheet_stick_page.dart +++ b/lib/widget/demo_draggable_sheet_stick_page.dart @@ -3,7 +3,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class DemoDraggableSheetStickPage extends StatefulWidget { - const DemoDraggableSheetStickPage({Key? key}) : super(key: key); + const DemoDraggableSheetStickPage({super.key}); @override State createState() => @@ -19,7 +19,7 @@ class _DemoDraggableSheetStickPageState } class DraggableScrollablePage extends StatefulWidget { - const DraggableScrollablePage({Key? key}) : super(key: key); + const DraggableScrollablePage({super.key}); @override State createState() => @@ -28,7 +28,7 @@ class DraggableScrollablePage extends StatefulWidget { class _DraggableScrollablePageState extends State with SingleTickerProviderStateMixin { - var controller = new DraggableScrollableController(); + var controller = DraggableScrollableController(); @override Widget build(BuildContext context) { @@ -38,9 +38,9 @@ class _DraggableScrollablePageState extends State ), body: Stack( children: [ - new Container( + Container( height: 300, - decoration: BoxDecoration( + decoration: const BoxDecoration( image: DecorationImage( image: AssetImage( "static/gsy_cat.png", @@ -54,7 +54,7 @@ class _DraggableScrollablePageState extends State controller: controller, builder: (BuildContext context, ScrollController scrollController) { - List _sliverList(int sliverChildCount) { + List sliverList(int sliverChildCount) { List widgetList = []; widgetList ..add( @@ -96,7 +96,7 @@ class _DraggableScrollablePageState extends State color: Colors.blue[100], child: CustomScrollView( controller: scrollController, - slivers: _sliverList(25), + slivers: sliverList(25), ), ); }, @@ -107,7 +107,7 @@ class _DraggableScrollablePageState extends State floatingActionButton: FloatingActionButton( onPressed: () { controller.animateTo(1, - duration: Duration(milliseconds: 200), curve: Curves.linear); + duration: const Duration(milliseconds: 200), curve: Curves.linear); }, ), ); @@ -161,7 +161,7 @@ class GSYSliverHeaderDelegate extends SliverPersistentHeaderDelegate { FloatingHeaderSnapConfiguration get snapConfiguration => snapConfig; } -typedef Widget Builder( +typedef Builder = Widget Function( BuildContext context, double shrinkOffset, bool overlapsContent); @@ -175,9 +175,9 @@ Widget build(BuildContext context) { ), body: Stack( children: [ - new Container( + Container( height: 300, - decoration: BoxDecoration( + decoration: const BoxDecoration( image: DecorationImage( image: AssetImage( "static/gsy_cat.png", @@ -195,7 +195,7 @@ Widget build(BuildContext context) { Align( alignment: Alignment.topCenter, child: Container( - margin: EdgeInsets.symmetric(vertical: 8), + margin: const EdgeInsets.symmetric(vertical: 8), height: 8.0, width: 70.0, decoration: BoxDecoration( @@ -203,7 +203,7 @@ Widget build(BuildContext context) { borderRadius: BorderRadius.circular(10.0)), ), ), - SizedBox(height: 16), + const SizedBox(height: 16), Expanded( child: Container( color: Colors.blue[100], diff --git a/lib/widget/demo_navigator_new.dart b/lib/widget/demo_navigator_new.dart index 68cbb66..5108efe 100644 --- a/lib/widget/demo_navigator_new.dart +++ b/lib/widget/demo_navigator_new.dart @@ -8,13 +8,15 @@ class Book { } class BooksApp extends StatefulWidget { + const BooksApp({super.key}); + @override State createState() => _BooksAppState(); } class _BooksAppState extends State { - BookRouterDelegate _routerDelegate = BookRouterDelegate(); - BookRouteInformationParser _routeInformationParser = + final BookRouterDelegate _routerDelegate = BookRouterDelegate(); + final BookRouteInformationParser _routeInformationParser = BookRouteInformationParser(); @override @@ -33,7 +35,7 @@ class BookRouteInformationParser extends RouteInformationParser { RouteInformation routeInformation) async { final uri = routeInformation.uri; // Handle '/' - if (uri.pathSegments.length == 0) { + if (uri.pathSegments.isEmpty) { return BookRoutePath.home(); } @@ -51,15 +53,15 @@ class BookRouteInformationParser extends RouteInformationParser { } @override - RouteInformation? restoreRouteInformation(BookRoutePath path) { - if (path.isUnknown) { + RouteInformation? restoreRouteInformation(BookRoutePath configuration) { + if (configuration.isUnknown) { return RouteInformation(uri: Uri.parse('/404')); } - if (path.isHomePage) { + if (configuration.isHomePage) { return RouteInformation(uri: Uri.parse('/')); } - if (path.isDetailsPage) { - return RouteInformation(uri: Uri.parse('/book/${path.id}')); + if (configuration.isDetailsPage) { + return RouteInformation(uri: Uri.parse('/book/${configuration.id}')); } return null; } @@ -67,6 +69,7 @@ class BookRouteInformationParser extends RouteInformationParser { class BookRouterDelegate extends RouterDelegate with ChangeNotifier, PopNavigatorRouterDelegateMixin { + @override final GlobalKey navigatorKey; Book? _selectedBook; @@ -80,6 +83,7 @@ class BookRouterDelegate extends RouterDelegate BookRouterDelegate() : navigatorKey = GlobalKey(); + @override BookRoutePath get currentConfiguration { if (show404) { return BookRoutePath.unknown(); @@ -95,14 +99,14 @@ class BookRouterDelegate extends RouterDelegate key: navigatorKey, pages: [ MaterialPage( - key: ValueKey('BooksListPage'), + key: const ValueKey('BooksListPage'), child: BooksListScreen( books: books, onTapped: _handleBookTapped, ), ), if (show404) - MaterialPage(key: ValueKey('UnknownPage'), child: UnknownScreen()) + const MaterialPage(key: ValueKey('UnknownPage'), child: UnknownScreen()) else if (_selectedBook != null) BookDetailsPage(book: _selectedBook) ], @@ -122,20 +126,20 @@ class BookRouterDelegate extends RouterDelegate } @override - Future setNewRoutePath(BookRoutePath path) async { - if (path.isUnknown) { + Future setNewRoutePath(BookRoutePath configuration) async { + if (configuration.isUnknown) { _selectedBook = null; show404 = true; return; } - if (path.isDetailsPage) { - if (path.id! < 0 || path.id! > books.length - 1) { + if (configuration.isDetailsPage) { + if (configuration.id! < 0 || configuration.id! > books.length - 1) { show404 = true; return; } - _selectedBook = books[path.id!]; + _selectedBook = books[configuration.id!]; } else { _selectedBook = null; } @@ -156,6 +160,7 @@ class BookDetailsPage extends Page { this.book, }) : super(key: ValueKey(book)); + @override Route createRoute(BuildContext context) { return MaterialPageRoute( settings: this, @@ -189,7 +194,7 @@ class BooksListScreen extends StatelessWidget { final List books; final ValueChanged onTapped; - BooksListScreen({ + const BooksListScreen({super.key, required this.books, required this.onTapped, }); @@ -215,7 +220,7 @@ class BooksListScreen extends StatelessWidget { class BookDetailsScreen extends StatelessWidget { final Book? book; - BookDetailsScreen({ + const BookDetailsScreen({super.key, required this.book, }); @@ -241,11 +246,13 @@ class BookDetailsScreen extends StatelessWidget { } class UnknownScreen extends StatelessWidget { + const UnknownScreen({super.key}); + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), - body: Center( + body: const Center( child: Text('404!'), ), ); diff --git a/lib/widget/drag_img_demo_page.dart b/lib/widget/drag_img_demo_page.dart index d8a7f6f..3ebb2b8 100644 --- a/lib/widget/drag_img_demo_page.dart +++ b/lib/widget/drag_img_demo_page.dart @@ -2,6 +2,8 @@ import 'package:flutter/material.dart'; import 'package:matrix_gesture_detector/matrix_gesture_detector.dart'; class DragImgDemoPage extends StatefulWidget { + const DragImgDemoPage({super.key}); + @override _DragImgDemoPageState createState() => _DragImgDemoPageState(); } @@ -14,30 +16,28 @@ class _DragImgDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("DragImgDemoPage"), + title: const Text("DragImgDemoPage"), ), - body: new Container( - child: MatrixGestureDetector( - onMatrixUpdate: (m, tm, sm, rm) { - setState(() { - transform = m; - }); - }, - child: Transform( - transform: transform, - child: new Image.asset( - "static/gsy_cat.png", - fit: BoxFit.fitWidth, - width: MediaQuery - .of(context) - .size - .width, - height: MediaQuery - .of(context) - .size - .height, - ) - ), + body: MatrixGestureDetector( + onMatrixUpdate: (m, tm, sm, rm) { + setState(() { + transform = m; + }); + }, + child: Transform( + transform: transform, + child: Image.asset( + "static/gsy_cat.png", + fit: BoxFit.fitWidth, + width: MediaQuery + .of(context) + .size + .width, + height: MediaQuery + .of(context) + .size + .height, + ) ), ), ); diff --git a/lib/widget/drop_select_menu/drop_select_controller.dart b/lib/widget/drop_select_menu/drop_select_controller.dart index 2efb86c..66f5921 100644 --- a/lib/widget/drop_select_menu/drop_select_controller.dart +++ b/lib/widget/drop_select_menu/drop_select_controller.dart @@ -34,6 +34,7 @@ class DropSelectController extends ChangeNotifier { enum DropSelectEvent { SELECT, + // ignore: constant_identifier_names ACTIVE, HIDE, } diff --git a/lib/widget/drop_select_menu/drop_select_demo_page.dart b/lib/widget/drop_select_menu/drop_select_demo_page.dart index fea8190..32cd2b0 100644 --- a/lib/widget/drop_select_menu/drop_select_demo_page.dart +++ b/lib/widget/drop_select_menu/drop_select_demo_page.dart @@ -10,6 +10,8 @@ import 'drop_select_list_menu.dart'; import 'drop_select_menu.dart'; class DropSelectDemoPage extends StatefulWidget { + const DropSelectDemoPage({super.key}); + @override _DropSelectDemoPageState createState() => _DropSelectDemoPageState(); } @@ -26,7 +28,7 @@ class _DropSelectDemoPageState extends State { } DropSelectHeader renderDropSelectHeader() { - return new DropSelectHeader( + return DropSelectHeader( titles: [selectChildGrid[0], selectExpand[0], selectNormal[0]], showTitle: (_, index) { switch (index) { @@ -43,28 +45,28 @@ class _DropSelectDemoPageState extends State { } DropSelectMenu renderDropSelectMenu() { - return new DropSelectMenu( + return DropSelectMenu( maxMenuHeight: MediaQuery.sizeOf(context).height, menus: [ - new DropSelectMenuBuilder( + DropSelectMenuBuilder( builder: (BuildContext context) { - return new DropSelectExpandedListMenu( + return DropSelectExpandedListMenu( data: selectExpand, itemBuilder: renderSelectItemGrid, ); }, height: MediaQuery.sizeOf(context).height), - new DropSelectMenuBuilder( + DropSelectMenuBuilder( builder: (BuildContext context) { - return new DropSelectGridListMenu( + return DropSelectGridListMenu( data: selectChildGrid, itemBuilder: renderSelectItemGrid, ); }, height: MediaQuery.sizeOf(context).height), - new DropSelectMenuBuilder( + DropSelectMenuBuilder( builder: (BuildContext context) { - return new DropSelectListMenu( + return DropSelectListMenu( data: selectNormal, singleSelected: true, itemBuilder: renderSelectItem, @@ -75,24 +77,24 @@ class _DropSelectDemoPageState extends State { } Widget renderSelectItem(BuildContext context, DropSelectObject data) { - return new Padding( - padding: new EdgeInsets.all(10.0), - child: new Row( + return Padding( + padding: const EdgeInsets.all(10.0), + child: Row( children: [ - new Text( + Text( data.title!, style: data.selected - ? new TextStyle( + ? TextStyle( fontSize: 14.0, color: Theme.of(context).primaryColor, fontWeight: FontWeight.w400) - : new TextStyle(fontSize: 14.0), + : const TextStyle(fontSize: 14.0), ), - new Expanded( - child: new Align( + Expanded( + child: Align( alignment: Alignment.centerRight, child: data.selected - ? new Icon( + ? Icon( Icons.check_circle, color: Theme.of(context).primaryColor, ) @@ -103,9 +105,9 @@ class _DropSelectDemoPageState extends State { } Widget renderSelectItemGrid(BuildContext context, DropSelectObject data) { - return new Container( - padding: new EdgeInsets.all(10.0), - child: new Container( + return Container( + padding: const EdgeInsets.all(10.0), + child: Container( alignment: Alignment.center, decoration: BoxDecoration( border: Border.all( @@ -113,14 +115,14 @@ class _DropSelectDemoPageState extends State { data.selected ? Theme.of(context).primaryColor : Colors.grey, width: 1.0), ), - child: new Text( + child: Text( data.title!, style: data.selected - ? new TextStyle( + ? TextStyle( fontSize: 14.0, color: Theme.of(context).primaryColor, fontWeight: FontWeight.w400) - : new TextStyle(fontSize: 14.0), + : const TextStyle(fontSize: 14.0), ), ), ); @@ -130,35 +132,33 @@ class _DropSelectDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("DropSelectDemoPage"), + title: const Text("DropSelectDemoPage"), ), - body: Container( - child: new DropSelectMenuContainer( - child: new Column( - children: [ - renderDropSelectHeader(), - new Expanded( - child: new Stack( - children: [ - new ListView( - children: List.generate(100, (index) { - return Container( - height: 40, - margin: EdgeInsets.only(left: 10), - child: new Text("Text $index"), - ); - }), - ), - new Column( - children: [ - new Expanded(child: renderDropSelectMenu()), - ], - ) - ], - ), - ) - ], - ), + body: DropSelectMenuContainer( + child: Column( + children: [ + renderDropSelectHeader(), + Expanded( + child: Stack( + children: [ + ListView( + children: List.generate(100, (index) { + return Container( + height: 40, + margin: const EdgeInsets.only(left: 10), + child: Text("Text $index"), + ); + }), + ), + Column( + children: [ + Expanded(child: renderDropSelectMenu()), + ], + ) + ], + ), + ) + ], ), ), ); diff --git a/lib/widget/drop_select_menu/drop_select_expanded_menu.dart b/lib/widget/drop_select_menu/drop_select_expanded_menu.dart index 68814f3..f18adc5 100644 --- a/lib/widget/drop_select_menu/drop_select_expanded_menu.dart +++ b/lib/widget/drop_select_menu/drop_select_expanded_menu.dart @@ -9,7 +9,7 @@ import 'drop_select_widget.dart'; const double kDropExpendedSelectMenuItemHeight = 45.0; -typedef Widget MenuItemExpandedBuilder( +typedef MenuItemExpandedBuilder = Widget Function( BuildContext context, T data); class DropSelectExpandedListMenu @@ -19,21 +19,21 @@ class DropSelectExpandedListMenu final bool singleSelected; final MenuItemExpandedBuilder? itemBuilder; - DropSelectExpandedListMenu( - {this.data, + const DropSelectExpandedListMenu( + {super.key, this.data, this.itemBuilder, this.singleSelected = false, this.itemExtent = kDropExpendedSelectMenuItemHeight}); @override DropSelectState createState() { - return new _MenuListExpandedState(); + return _MenuListExpandedState(); } } class _MenuListExpandedState extends DropSelectState> { - Map cleanOtherList = new HashMap(); + Map cleanOtherList = HashMap(); final List _controllers = []; @@ -52,41 +52,41 @@ class _MenuListExpandedState } hideAllExpandController() { - _controllers.forEach((controller) { + for (var controller in _controllers) { controller.expanded = false; - }); + } } Widget renderButton() { - return new Container( + return SizedBox( height: 50, - child: new Row( + child: Row( children: [ - new Expanded( - child: new TextButton( + Expanded( + child: TextButton( onPressed: () { setState(() { resetList(widget.data!); }); controller!.hide(); }, - child: new Text("重置"))), - new Expanded( - child: new TextButton( + child: const Text("重置"))), + Expanded( + child: TextButton( onPressed: () { controller!.select(_cloneList); }, - child: new Text("确定"))), + child: const Text("确定"))), ], ), ); } renderGrid(count, data, index) { - return new Container( + return SizedBox( height: widget.itemExtent * count, child: GridView.count( - physics: NeverScrollableScrollPhysics(), + physics: const NeverScrollableScrollPhysics(), crossAxisCount: 2, childAspectRatio: 3, children: List.generate(count, (i) { @@ -94,7 +94,7 @@ class _MenuListExpandedState if (child.selectedCleanOther) { cleanOtherList["$i"] = i; } - return new InkWell( + return InkWell( onTap: () { if (widget.singleSelected) { data.forEach((item) { @@ -106,7 +106,7 @@ class _MenuListExpandedState item.selected = false; }); } - if (!child.selectedCleanOther && cleanOtherList.length > 0) { + if (!child.selectedCleanOther && cleanOtherList.isNotEmpty) { cleanOtherList.forEach((key, value) { if (value != i) { data.children[value].selected = false; @@ -126,39 +126,37 @@ class _MenuListExpandedState @override Widget build(BuildContext context) { - return Container( - child: new Column( - children: [ - new Expanded( - child: new ListView.builder( - itemBuilder: (context, index) { - return ExpandablePanel( + return Column( + children: [ + Expanded( + child: ListView.builder( + itemBuilder: (context, index) { + return ExpandablePanel( + height: widget.itemExtent, + initialExpanded: _controllers[index].expanded, + controller: _controllers[index], + header: Container( height: widget.itemExtent, - initialExpanded: _controllers[index].expanded, - controller: _controllers[index], - header: new Container( - height: widget.itemExtent, - padding: EdgeInsets.only(left: 10), - child: new Align( - alignment: Alignment.centerLeft, - child: Text( - _cloneList[index].title!, - style: TextStyle(fontSize: 16, color: Colors.black), - ), + padding: const EdgeInsets.only(left: 10), + child: Align( + alignment: Alignment.centerLeft, + child: Text( + _cloneList[index].title!, + style: const TextStyle(fontSize: 16, color: Colors.black), ), ), - expanded: renderGrid(_cloneList[index].children!.length, - _cloneList[index], index), - tapHeaderToExpand: true, - hasIcon: true, - ); - }, - itemCount: _cloneList.length, - ), + ), + expanded: renderGrid(_cloneList[index].children!.length, + _cloneList[index], index), + tapHeaderToExpand: true, + hasIcon: true, + ); + }, + itemCount: _cloneList.length, ), - renderButton(), - ], - ), + ), + renderButton(), + ], ); } diff --git a/lib/widget/drop_select_menu/drop_select_grid_menu.dart b/lib/widget/drop_select_menu/drop_select_grid_menu.dart index c2911ad..0f03bdb 100644 --- a/lib/widget/drop_select_menu/drop_select_grid_menu.dart +++ b/lib/widget/drop_select_menu/drop_select_grid_menu.dart @@ -8,7 +8,7 @@ import 'drop_select_widget.dart'; const double kDropExpendedSelectMenuItemHeight = 45.0; -typedef Widget MenuItemGridBuilder( +typedef MenuItemGridBuilder = Widget Function( BuildContext context, T data); class DropSelectGridListMenu @@ -18,21 +18,21 @@ class DropSelectGridListMenu final bool singleSelected; final MenuItemGridBuilder? itemBuilder; - DropSelectGridListMenu( - {this.data, + const DropSelectGridListMenu( + {super.key, this.data, this.itemBuilder, this.singleSelected = false, this.itemExtent = kDropExpendedSelectMenuItemHeight}); @override DropSelectState createState() { - return new _MenuListGridState(); + return _MenuListGridState(); } } class _MenuListGridState extends DropSelectState> { - Map cleanOtherList = new HashMap(); + Map cleanOtherList = HashMap(); ///clone列表,深度拷贝,仅在确定选择后才复制到 widget.data final List _cloneList = []; @@ -47,10 +47,10 @@ class _MenuListGridState ///绘制 grid 列表嵌套 renderGrid(count, data, index) { - return new Container( + return SizedBox( height: widget.itemExtent * count, child: GridView.count( - physics: NeverScrollableScrollPhysics(), + physics: const NeverScrollableScrollPhysics(), crossAxisCount: 2, childAspectRatio: 3, children: List.generate(count, (i) { @@ -61,7 +61,7 @@ class _MenuListGridState cleanOtherList["$i"] = i; } - return new InkWell( + return InkWell( onTap: () { ///是否单选 @@ -78,7 +78,7 @@ class _MenuListGridState } ///如果存在冲突选择,需要处理 - if (!child.selectedCleanOther && cleanOtherList.length > 0) { + if (!child.selectedCleanOther && cleanOtherList.isNotEmpty) { cleanOtherList.forEach((key, value) { if (value != i) { data.children[value].selected = false; @@ -100,25 +100,25 @@ class _MenuListGridState ///绘制底部按键 Widget renderButton() { - return new Container( + return SizedBox( height: 50, - child: new Row( + child: Row( children: [ - new Expanded( - child: new TextButton( + Expanded( + child: TextButton( onPressed: () { setState(() { resetList(widget.data!); }); controller!.hide(); }, - child: new Text("重置"))), - new Expanded( - child: new TextButton( + child: const Text("重置"))), + Expanded( + child: TextButton( onPressed: () { controller!.select(_cloneList); }, - child: new Text("确定"))), + child: const Text("确定"))), ], ), ); @@ -126,30 +126,29 @@ class _MenuListGridState @override Widget build(BuildContext context) { - return Container( - child: new Column(children: [ - new Expanded( - child: new ListView.builder( - itemBuilder: (context, index) { - return new Container( - child: new Column( - children: [ - new Container( - child: new Text(_cloneList[index].title!), - alignment: Alignment.centerLeft, - ), - renderGrid(_cloneList[index].children!.length, - _cloneList[index], index) - ], - ), - ); - }, - itemCount: _cloneList.length, - ), + return Column(children: [ + Expanded( + child: ListView.builder( + itemBuilder: (context, index) { + // ignore: avoid_unnecessary_containers + return Container( + child: Column( + children: [ + Container( + alignment: Alignment.centerLeft, + child: Text(_cloneList[index].title!), + ), + renderGrid(_cloneList[index].children!.length, + _cloneList[index], index) + ], + ), + ); + }, + itemCount: _cloneList.length, ), - renderButton(), - ]), - ); + ), + renderButton(), + ]); } @override diff --git a/lib/widget/drop_select_menu/drop_select_header.dart b/lib/widget/drop_select_menu/drop_select_header.dart index 2ec1030..86dcf26 100644 --- a/lib/widget/drop_select_menu/drop_select_header.dart +++ b/lib/widget/drop_select_menu/drop_select_header.dart @@ -3,9 +3,9 @@ import 'package:gsy_flutter_demo/widget/drop_select_menu/drop_select_widget.dart import 'drop_select_controller.dart'; -typedef void DropdownMenuHeadTapCallback(int index); +typedef DropdownMenuHeadTapCallback = void Function(int index); -typedef String ShowTitle(dynamic data, int? index); +typedef ShowTitle = String Function(dynamic data, int? index); class DropSelectHeader extends DropSelectWidget { final List titles; @@ -19,17 +19,16 @@ class DropSelectHeader extends DropSelectWidget { DropSelectHeader({ required this.titles, this.activeIndex, - DropSelectController? controller, + super.controller, this.onTap, - Key? key, + super.key, this.height = 46.0, this.showTitle, - }) : assert(titles.length > 0), - super(key: key, controller: controller); + }) : assert(titles.isNotEmpty); @override DropSelectState createState() { - return new _DropSelectHeaderState(); + return _DropSelectHeaderState(); } } @@ -40,24 +39,24 @@ class _DropSelectHeaderState extends DropSelectState { final Color unselectedColor = Theme.of(context).unselectedWidgetColor; final ShowTitle showTitle = widget.showTitle!; - return new GestureDetector( + return GestureDetector( behavior: HitTestBehavior.opaque, - child: new Padding( - padding: new EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0), - child: new DecoratedBox( - decoration: new BoxDecoration( - border: new Border(left: Divider.createBorderSide(context))), - child: new Center( - child: new Row( + child: Padding( + padding: const EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0), + child: DecoratedBox( + decoration: BoxDecoration( + border: Border(left: Divider.createBorderSide(context))), + child: Center( + child: Row( mainAxisSize: MainAxisSize.min, children: [ - new Text( + Text( showTitle(title, index), - style: new TextStyle( + style: TextStyle( color: selected ? primaryColor : unselectedColor, ), ), - new Icon( + Icon( selected ? Icons.arrow_drop_up : Icons.arrow_drop_down, color: selected ? primaryColor : unselectedColor, ) @@ -95,24 +94,24 @@ class _DropSelectHeaderState extends DropSelectState { } list = list.map((Widget widget) { - return new Expanded( + return Expanded( child: widget, ); }).toList(); - final Decoration decoration = new BoxDecoration( - border: new Border( + final Decoration decoration = BoxDecoration( + border: Border( bottom: Divider.createBorderSide(context), ), ); - return new DecoratedBox( + return DecoratedBox( decoration: decoration, - child: new SizedBox( - child: new Row( + child: SizedBox( + height: height, + child: Row( children: list, - ), - height: height), + )), ); } diff --git a/lib/widget/drop_select_menu/drop_select_list_menu.dart b/lib/widget/drop_select_menu/drop_select_list_menu.dart index 1b43d3b..60c911c 100644 --- a/lib/widget/drop_select_menu/drop_select_list_menu.dart +++ b/lib/widget/drop_select_menu/drop_select_list_menu.dart @@ -5,7 +5,7 @@ import 'package:gsy_flutter_demo/widget/drop_select_menu/drop_select_object.dart import 'drop_select_controller.dart'; import 'drop_select_widget.dart'; -typedef Widget MenuItemBuilder( +typedef MenuItemBuilder = Widget Function( BuildContext context, T data); const double kDropSelectMenuItemHeight = 45.0; @@ -16,15 +16,15 @@ class DropSelectListMenu extends DropSelectWidget { final bool singleSelected; final double itemExtent; - DropSelectListMenu( - {this.data, + const DropSelectListMenu( + {super.key, this.data, this.singleSelected = false, this.itemBuilder, this.itemExtent = kDropSelectMenuItemHeight}); @override DropSelectState createState() { - return new _MenuListState(); + return _MenuListState(); } } @@ -39,19 +39,19 @@ class _MenuListState final List list = widget.data!; final T data = list[index]; - return new GestureDetector( + return GestureDetector( behavior: HitTestBehavior.opaque, child: widget.itemBuilder!(context, data), onTap: () { if (widget.singleSelected) { - widget.data!.forEach((item) { + for (var item in widget.data!) { item.selected = false; - }); + } } if(data.selectedCleanOther) { - widget.data!.forEach((item) { + for (var item in widget.data!) { item.selected = false; - }); + } } setState(() { data.selected = !data.selected; @@ -63,7 +63,7 @@ class _MenuListState @override Widget build(BuildContext context) { - return new ListView.builder( + return ListView.builder( itemExtent: widget.itemExtent, itemBuilder: buildItem, itemCount: widget.data!.length, diff --git a/lib/widget/drop_select_menu/drop_select_menu.dart b/lib/widget/drop_select_menu/drop_select_menu.dart index 2e2e22b..52e8b30 100644 --- a/lib/widget/drop_select_menu/drop_select_menu.dart +++ b/lib/widget/drop_select_menu/drop_select_menu.dart @@ -1,5 +1,6 @@ import 'dart:async'; import 'dart:ui' as ui show ImageFilter; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'drop_rect_tween.dart'; @@ -30,28 +31,27 @@ class DropSelectMenu extends DropSelectWidget { final double? maxMenuHeight; - DropSelectMenu( + const DropSelectMenu( {required this.menus, - DropSelectController? controller, + super.controller, Duration? hideDuration, Duration? showDuration, this.onHide, this.blur, - Key? key, + super.key, this.maxMenuHeight, Curve? hideCurve, this.switchStyle = DropSelectMenuSwitchStyle .animationShowUntilAnimationHideComplete, Curve? showCurve}) - : hideDuration = hideDuration ?? new Duration(milliseconds: 150), - showDuration = showDuration ?? new Duration(milliseconds: 300), + : hideDuration = hideDuration ?? const Duration(milliseconds: 150), + showDuration = showDuration ?? const Duration(milliseconds: 300), showCurve = showCurve ?? Curves.fastOutSlowIn, - hideCurve = hideCurve ?? Curves.fastOutSlowIn, - super(key: key, controller: controller); + hideCurve = hideCurve ?? Curves.fastOutSlowIn; @override DropSelectState createState() { - return new _DropSelectMenuState(); + return _DropSelectMenuState(); } } @@ -61,13 +61,13 @@ class _DropSelectAnimation { late DropRectTween position; _DropSelectAnimation(TickerProvider provider) { - animationController = new AnimationController(vsync: provider); + animationController = AnimationController(vsync: provider); } set height(double value) { - position = new DropRectTween( - begin: new Rect.fromLTRB(0.0, -value, 0.0, 0.0), - end: new Rect.fromLTRB(0.0, 0.0, 0.0, 0.0), + position = DropRectTween( + begin: Rect.fromLTRB(0.0, -value, 0.0, 0.0), + end: const Rect.fromLTRB(0.0, 0.0, 0.0, 0.0), ); rect = position.animate(animationController); @@ -90,7 +90,7 @@ class _DropSelectAnimation { class SizeClipper extends CustomClipper { @override Rect getClip(Size size) { - return new Rect.fromLTWH(0.0, 0.0, size.width, size.height); + return Rect.fromLTWH(0.0, 0.0, size.width, size.height); } @override @@ -113,15 +113,15 @@ class _DropSelectMenuState extends DropSelectState _showing = []; _dropSelectAnimations = []; for (int i = 0, c = widget.menus.length; i < c; ++i) { - _dropSelectAnimations.add(new _DropSelectAnimation(this)); + _dropSelectAnimations.add(_DropSelectAnimation(this)); } _updateHeights(); _show = false; - _fadeController = new AnimationController(vsync: this); - _fadeAnimation = new Tween( + _fadeController = AnimationController(vsync: this); + _fadeAnimation = Tween( begin: 0.0, end: 1.0, ).animate(_fadeController); @@ -155,21 +155,21 @@ class _DropSelectMenuState extends DropSelectState Widget createMenu(BuildContext context, DropSelectMenuBuilder menu, int i) { DropSelectMenuBuilder builder = menu; - return new ClipRect( - clipper: new SizeClipper(), - child: new SizedBox( + return ClipRect( + clipper: SizeClipper(), + child: SizedBox( height: _ensureHeight(builder.height), child: _showing.contains(i) ? builder.builder(context) : null), ); } Widget _buildBackground(BuildContext context) { - Widget container = new Container( + Widget container = Container( color: Colors.black26, ); - container = new BackdropFilter( - filter: new ui.ImageFilter.blur( + container = BackdropFilter( + filter: ui.ImageFilter.blur( sigmaY: widget.blur ?? 0, sigmaX: widget.blur ?? 0, ), @@ -182,25 +182,27 @@ class _DropSelectMenuState extends DropSelectState Widget build(BuildContext context) { List list = []; - print("build ${new DateTime.now()}"); + if (kDebugMode) { + print("build ${DateTime.now()}"); + } if (_show) { list.add( - new FadeTransition( + FadeTransition( opacity: _fadeAnimation, - child: new GestureDetector( + child: GestureDetector( onTap: onHide, child: _buildBackground(context)), ), ); } for (int i = 0, c = widget.menus.length; i < c; ++i) { - list.add(new RelativePositionedTransition( + list.add(RelativePositionedTransition( rect: _dropSelectAnimations[i].rect, - size: new Size(0.0, 0.0), - child: new Align( + size: const Size(0.0, 0.0), + child: Align( alignment: Alignment.topCenter, - child: new Container( + child: Container( color: Theme.of(context).scaffoldBackgroundColor, child: createMenu(context, widget.menus[i], i), )))); @@ -208,7 +210,7 @@ class _DropSelectMenuState extends DropSelectState //WidgetsBinding; //context.findRenderObject(); - return new Stack( + return Stack( fit: StackFit.expand, children: list, ); @@ -238,7 +240,7 @@ class _DropSelectMenuState extends DropSelectState return future; } - return new TickerFuture.complete(); + return TickerFuture.complete(); } TickerFuture _hide(int index) { @@ -273,7 +275,7 @@ class _DropSelectMenuState extends DropSelectState _show = true; }); - return new Future.value(null); + return Future.value(null); } case DropSelectMenuSwitchStyle.animationHideAnimationShow: { diff --git a/lib/widget/drop_select_menu/drop_select_widget.dart b/lib/widget/drop_select_menu/drop_select_widget.dart index d7ade97..0cae3c6 100644 --- a/lib/widget/drop_select_menu/drop_select_widget.dart +++ b/lib/widget/drop_select_menu/drop_select_widget.dart @@ -6,7 +6,7 @@ import 'drop_select_controller.dart'; abstract class DropSelectWidget extends StatefulWidget { final DropSelectController? controller; - DropSelectWidget({Key? key, this.controller}) : super(key: key); + const DropSelectWidget({super.key, this.controller}); @override DropSelectState createState(); @@ -40,27 +40,27 @@ abstract class DropSelectState extends State { cloneDataList(List form, List to) { to.clear(); - form.forEach((item) { + for (var item in form) { to.add(item.clone()); - }); + } } resetList(List list) { - list.forEach((item) { + for (var item in list) { item.selected = false; item.children?.forEach((child) { child.selected = false; }); - }); + } selectChildFirst(list); } selectChildFirst(List list) { - list.forEach((item) { + for (var item in list) { if (item.children != null) { item.children![0].selected = true; } - }); + } } void _onEvent() { @@ -71,11 +71,11 @@ abstract class DropSelectState extends State { } class DropSelectMenuContainer extends StatefulWidget { - DropSelectMenuContainer({ - Key? key, + const DropSelectMenuContainer({ + super.key, required this.child, this.onSelected, - }) : super(key: key); + }); final Widget child; @@ -83,7 +83,7 @@ class DropSelectMenuContainer extends StatefulWidget { @override _DropSelectMenuContainerState createState() => - new _DropSelectMenuContainerState(); + _DropSelectMenuContainerState(); static DropSelectController? of(BuildContext context) { final _DropSelectMenuInherited? scope = @@ -99,7 +99,7 @@ class _DropSelectMenuContainerState extends State @override void initState() { super.initState(); - _controller = new DropSelectController(); + _controller = DropSelectController(); _controller!.addListener(_onController); } @@ -131,7 +131,7 @@ class _DropSelectMenuContainerState extends State @override Widget build(BuildContext context) { - return new _DropSelectMenuInherited( + return _DropSelectMenuInherited( controller: _controller, enable: TickerMode.of(context), child: widget.child, @@ -141,8 +141,7 @@ class _DropSelectMenuContainerState extends State class _DropSelectMenuInherited extends InheritedWidget { const _DropSelectMenuInherited( - {Key? key, this.controller, this.enable, required Widget child}) - : super(key: key, child: child); + {this.controller, this.enable, required super.child}); final bool? enable; final DropSelectController? controller; @@ -160,4 +159,4 @@ class DropSelectMenuBuilder { DropSelectMenuBuilder({required this.builder, this.height}); } -typedef DropOnSelected({int? menuIndex, int? index, dynamic data}); +typedef DropOnSelected = Function({int? menuIndex, int? index, dynamic data}); diff --git a/lib/widget/expand/expand_widget.dart b/lib/widget/expand/expand_widget.dart index 4047eb8..0886e57 100644 --- a/lib/widget/expand/expand_widget.dart +++ b/lib/widget/expand/expand_widget.dart @@ -7,15 +7,14 @@ class ExpandableNotifier extends StatefulWidget { final Duration? animationDuration; final Widget? child; - ExpandableNotifier( - {Key? key, + const ExpandableNotifier( + {super.key, this.controller, this.initialExpanded, this.animationDuration, required this.child}) : assert(!(controller != null && animationDuration != null)), - assert(!(controller != null && initialExpanded != null)), - super(key: key); + assert(!(controller != null && initialExpanded != null)); @override _ExpandableNotifierState createState() => _ExpandableNotifierState(); @@ -43,9 +42,9 @@ class _ExpandableNotifierState extends State { class _ExpandableInheritedNotifier extends InheritedNotifier { - _ExpandableInheritedNotifier( - {required ExpandableController? controller, required Widget child}) - : super(notifier: controller, child: child); + const _ExpandableInheritedNotifier( + {required ExpandableController? controller, required super.child}) + : super(notifier: controller); } class ExpandableController extends ValueNotifier { @@ -53,7 +52,7 @@ class ExpandableController extends ValueNotifier { final Duration animationDuration; ExpandableController({bool? initialExpanded, Duration? animationDuration}) - : this.animationDuration = + : animationDuration = animationDuration ?? const Duration(milliseconds: 300), super(initialExpanded ?? false); @@ -90,8 +89,8 @@ class Expandable extends StatelessWidget { final Curve fadeCurve; final Curve sizeCurve; - Expandable( - {this.collapsed, + const Expandable( + {super.key, this.collapsed, this.expanded, this.collapsedFadeStart = 0, this.collapsedFadeEnd = 1, @@ -121,7 +120,7 @@ class Expandable extends StatelessWidget { } } -typedef Widget ExpandableBuilder( +typedef ExpandableBuilder = Widget Function( BuildContext context, Widget? collapsed, Widget? expanded); /// Determines the placement of the expand/collapse icon in [ExpandablePanel] @@ -171,8 +170,8 @@ class ExpandablePanel extends StatelessWidget { ); } - ExpandablePanel( - {this.collapsed, + const ExpandablePanel( + {super.key, this.collapsed, this.height = 56.5, this.header, this.expanded, @@ -194,10 +193,10 @@ class ExpandablePanel extends StatelessWidget { Expanded( child: child, ), - new Center( - child: new Container( + Center( + child: SizedBox( height: height, - child: expandableIcon ?? ExpandableIcon(), + child: expandableIcon ?? const ExpandableIcon(), ), ) ]; @@ -214,7 +213,7 @@ class ExpandablePanel extends StatelessWidget { return tapHeaderToExpand ? ExpandableButton( child: ConstrainedBox( - constraints: BoxConstraints(minHeight: 45.0), child: child)) + constraints: const BoxConstraints(minHeight: 45.0), child: child)) : child ?? Container(); } @@ -233,7 +232,7 @@ class ExpandablePanel extends StatelessWidget { return ExpandableNotifier( controller: controller ?? ExpandableController(initialExpanded: initialExpanded), - child: this.header != null ? buildWithHeader() : buildWithoutHeader(), + child: header != null ? buildWithHeader() : buildWithoutHeader(), ); } } @@ -241,6 +240,8 @@ class ExpandablePanel extends StatelessWidget { /// An down/up arrow icon that toggles the state of [ExpandableController] when the user clicks on it. /// The model is accessed via [ScopedModelDescendant]. class ExpandableIcon extends StatelessWidget { + const ExpandableIcon({super.key}); + @override Widget build(BuildContext context) { final controller = ExpandableController.of(context)!; @@ -257,7 +258,7 @@ class ExpandableIcon extends StatelessWidget { class ExpandableButton extends StatelessWidget { final Widget? child; - ExpandableButton({this.child}); + const ExpandableButton({super.key, this.child}); @override Widget build(BuildContext context) { @@ -287,14 +288,14 @@ class ScrollOnExpand extends StatefulWidget { /// If true then the widget will be scrolled to become visible when collapsed final bool scrollOnCollapse; - ScrollOnExpand({ - Key? key, + const ScrollOnExpand({ + super.key, required this.child, this.scrollAnimationDuration = const Duration(milliseconds: 300), this.scrollOnExpand = true, this.scrollOnCollapse = true, - }): super(key: key); + }); @override _ScrollOnExpandState createState() => _ScrollOnExpandState(); @@ -343,7 +344,7 @@ class _ScrollOnExpandState extends State { _expandedStateChanged() { _isAnimating++; - Future.delayed(_controller!.animationDuration + Duration(milliseconds: 10), _animationComplete); + Future.delayed(_controller!.animationDuration + const Duration(milliseconds: 10), _animationComplete); } @override diff --git a/lib/widget/floating_touch_demo_page.dart b/lib/widget/floating_touch_demo_page.dart index 4264899..b177330 100644 --- a/lib/widget/floating_touch_demo_page.dart +++ b/lib/widget/floating_touch_demo_page.dart @@ -2,12 +2,14 @@ import 'package:flutter/material.dart'; ///全局悬浮按键 class FloatingTouchDemoPage extends StatefulWidget { + const FloatingTouchDemoPage({super.key}); + @override _FloatingTouchDemoPageState createState() => _FloatingTouchDemoPageState(); } class _FloatingTouchDemoPageState extends State { - Offset offset = Offset(200, 200); + Offset offset = const Offset(200, 200); final double height = 80; @@ -15,10 +17,10 @@ class _FloatingTouchDemoPageState extends State { _showFloating() { var overlayState = Overlay.of(context); OverlayEntry? overlayEntry; - overlayEntry = new OverlayEntry(builder: (context) { + overlayEntry = OverlayEntry(builder: (context) { return Stack( children: [ - new Positioned( + Positioned( left: offset.dx, top: offset.dy, child: _buildFloating(overlayEntry), @@ -47,7 +49,7 @@ class _FloatingTouchDemoPageState extends State { onLongPress: () { overlayEntry!.remove(); }, - child: new Material( + child: Material( color: Colors.transparent, child: Container( height: height, @@ -56,7 +58,7 @@ class _FloatingTouchDemoPageState extends State { decoration: BoxDecoration( color: Colors.redAccent, borderRadius: BorderRadius.all(Radius.circular(height / 2))), - child: new Text( + child: const Text( "长按\n移除", style: TextStyle(color: Colors.white), ), @@ -69,16 +71,14 @@ class _FloatingTouchDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("FloatingTouchDemoPage"), + title: const Text("FloatingTouchDemoPage"), ), - body: new Container( - child: Center( - child: TextButton( - onPressed: () { - _showFloating(); - }, - child: new Text("显示悬浮")), - ), + body: Center( + child: TextButton( + onPressed: () { + _showFloating(); + }, + child: const Text("显示悬浮")), ), ); } diff --git a/lib/widget/gradient_text_demo_page.dart b/lib/widget/gradient_text_demo_page.dart index 306d32f..b4fd58b 100644 --- a/lib/widget/gradient_text_demo_page.dart +++ b/lib/widget/gradient_text_demo_page.dart @@ -2,73 +2,67 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; class GradientTextDemoPage extends StatelessWidget { - const GradientTextDemoPage({Key? key}) : super(key: key); + const GradientTextDemoPage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("GradientTextDemoPage"), + title: const Text("GradientTextDemoPage"), ), - body: Container( - child: Center( - child: Stack( - alignment: Alignment.center, - children: [ - if (kIsWeb) - Align( - alignment: Alignment.topCenter, - child: Padding( - padding: EdgeInsets.only(top: 30), - child: Text("当前效果不支持 Web ,请在 App 查看"), - ), - ), - Container( - child: Text( - '8', - style: TextStyle( - fontSize: 100, - - /// 2.10 下因为有 shader (Gradient) , web 下会用 canvas - ///编译文本,此时会有 _applySpanStyleToCanvas 时 setUpPaint 的 Rect 为 nul 的问题 - ///所以添加 fontFeatures 可以在底层渲染时切换回 p+span 标签 - ///但是目前 p+span 不支持 foreground 的 Paint - fontFeatures: - kIsWeb ? [FontFeature.enable("tnum")] : null, - foreground: Paint() - ..style = PaintingStyle.fill - ..strokeWidth = 3 - ..shader = LinearGradient( - begin: Alignment.bottomLeft, - end: Alignment.topRight, - colors: [Colors.yellow, Colors.black]) - .createShader(Rect.fromLTWH(0, 0, 200, 100))), + body: Center( + child: Stack( + alignment: Alignment.center, + children: [ + if (kIsWeb) + const Align( + alignment: Alignment.topCenter, + child: Padding( + padding: EdgeInsets.only(top: 30), + child: Text("当前效果不支持 Web ,请在 App 查看"), ), ), - Container( - child: Text( - '8', - style: TextStyle( - fontSize: 100, + Text( + '8', + style: TextStyle( + fontSize: 100, - /// 2.10 下因为有 shader (Gradient) , web 下会用 canvas - ///编译文本,此时会有 _applySpanStyleToCanvas 时 setUpPaint 的 Rect 为 nul 的问题 - ///所以添加 fontFeatures 可以在底层渲染时切换回 p+span 标签 - ///但是目前 p+span 不支持 foreground 的 Paint - fontFeatures: - kIsWeb ? [FontFeature.enable("tnum")] : null, - foreground: Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = 2 - ..shader = LinearGradient( - begin: Alignment.bottomLeft, - end: Alignment.topRight, - colors: [Colors.limeAccent, Colors.cyanAccent]) - .createShader(Rect.fromLTWH(0, 0, 200, 100))), - ), - ), - ], - ), + /// 2.10 下因为有 shader (Gradient) , web 下会用 canvas + ///编译文本,此时会有 _applySpanStyleToCanvas 时 setUpPaint 的 Rect 为 nul 的问题 + ///所以添加 fontFeatures 可以在底层渲染时切换回 p+span 标签 + ///但是目前 p+span 不支持 foreground 的 Paint + fontFeatures: + kIsWeb ? [const FontFeature.enable("tnum")] : null, + foreground: Paint() + ..style = PaintingStyle.fill + ..strokeWidth = 3 + ..shader = const LinearGradient( + begin: Alignment.bottomLeft, + end: Alignment.topRight, + colors: [Colors.yellow, Colors.black]) + .createShader(const Rect.fromLTWH(0, 0, 200, 100))), + ), + Text( + '8', + style: TextStyle( + fontSize: 100, + + /// 2.10 下因为有 shader (Gradient) , web 下会用 canvas + ///编译文本,此时会有 _applySpanStyleToCanvas 时 setUpPaint 的 Rect 为 nul 的问题 + ///所以添加 fontFeatures 可以在底层渲染时切换回 p+span 标签 + ///但是目前 p+span 不支持 foreground 的 Paint + fontFeatures: + kIsWeb ? [const FontFeature.enable("tnum")] : null, + foreground: Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 2 + ..shader = const LinearGradient( + begin: Alignment.bottomLeft, + end: Alignment.topRight, + colors: [Colors.limeAccent, Colors.cyanAccent]) + .createShader(const Rect.fromLTWH(0, 0, 200, 100))), + ), + ], ), ), ); diff --git a/lib/widget/honor_demo_page.dart b/lib/widget/honor_demo_page.dart index 068a0ad..6aa9474 100644 --- a/lib/widget/honor_demo_page.dart +++ b/lib/widget/honor_demo_page.dart @@ -2,32 +2,32 @@ import 'package:flutter/material.dart'; ///共性元素动画 class HonorDemoPage extends StatelessWidget { + const HonorDemoPage({super.key}); + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("HonorDemoPage"), + title: const Text("HonorDemoPage"), ), - body: Container( - child: Center( - child: new InkWell( - onTap: () { - Navigator.of(context).push(new MaterialPageRoute( - builder: (context) { - return HonorPage(); - }, - fullscreenDialog: true)); - }, + body: Center( + child: InkWell( + onTap: () { + Navigator.of(context).push(MaterialPageRoute( + builder: (context) { + return const HonorPage(); + }, + fullscreenDialog: true)); + }, - /// Hero tag 共享 - child: new Hero( - tag: "image", - child: new Image.asset( - "static/gsy_cat.png", - fit: BoxFit.cover, - width: 100, - height: 100, - ), + /// Hero tag 共享 + child: Hero( + tag: "image", + child: Image.asset( + "static/gsy_cat.png", + fit: BoxFit.cover, + width: 100, + height: 100, ), ), ), @@ -37,19 +37,21 @@ class HonorDemoPage extends StatelessWidget { } class HonorPage extends StatelessWidget { + const HonorPage({super.key}); + @override Widget build(BuildContext context) { - return new Scaffold( + return Scaffold( backgroundColor: Colors.transparent, - body: new InkWell( + body: InkWell( onTap: () { Navigator.of(context).pop(); }, - child: new Container( + child: Container( alignment: Alignment.center, - child: new Hero( + child: Hero( tag: "image", - child: new Image.asset( + child: Image.asset( "static/gsy_cat.png", fit: BoxFit.cover, width: MediaQuery.sizeOf(context).width, diff --git a/lib/widget/index_stack_drag_card_demo_page.dart b/lib/widget/index_stack_drag_card_demo_page.dart index c1dfcfe..baae735 100644 --- a/lib/widget/index_stack_drag_card_demo_page.dart +++ b/lib/widget/index_stack_drag_card_demo_page.dart @@ -1,6 +1,9 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; class IndexStackDragCardDemoPage extends StatefulWidget { + const IndexStackDragCardDemoPage({super.key}); + @override State createState() => IndexStackDragCardDemoPageState(); } @@ -19,7 +22,7 @@ class IndexStackDragCardDemoPageState Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("IndexStackDragCardDemoPage"), + title: const Text("IndexStackDragCardDemoPage"), ), body: Stack(alignment: Alignment.center, children: getCardList()), ); @@ -29,8 +32,8 @@ class IndexStackDragCardDemoPageState setState(() { dataList.removeAt(index); }); - if (dataList.length == 0) { - Future.delayed(Duration(seconds: 0), () { + if (dataList.isEmpty) { + Future.delayed(const Duration(seconds: 0), () { setState(() { dataList = getDataList(); }); @@ -41,7 +44,9 @@ class IndexStackDragCardDemoPageState getCardItem(index, data) { return GestureDetector( onTap: () { - print("###### ${data.name}"); + if (kDebugMode) { + print("###### ${data.name}"); + } }, child: Card( elevation: 8.0, @@ -52,7 +57,7 @@ class IndexStackDragCardDemoPageState children: [ Container( decoration: BoxDecoration( - borderRadius: BorderRadius.only( + borderRadius: const BorderRadius.only( topLeft: Radius.circular(20.0), topRight: Radius.circular(20.0)), image: DecorationImage( @@ -62,10 +67,10 @@ class IndexStackDragCardDemoPageState width: 300.0, ), Container( - padding: EdgeInsets.symmetric(vertical: 10), + padding: const EdgeInsets.symmetric(vertical: 10), child: Text( data.name, - style: TextStyle( + style: const TextStyle( fontSize: 18.0, color: Colors.blue, ), @@ -86,9 +91,14 @@ class IndexStackDragCardDemoPageState cardList.add(Positioned.fill( child: UnconstrainedBox( child: Container( + margin: EdgeInsets.only( + top: (i < 5) ? 10 * i.toDouble() : 40, + left: (i < 5) ? 8 * i.toDouble() : 32), child: Draggable( onDragEnd: (drag) { - print("#### ${drag.velocity.pixelsPerSecond} ${drag.offset}"); + if (kDebugMode) { + print("#### ${drag.velocity.pixelsPerSecond} ${drag.offset}"); + } ///往下斜着拖 if (drag.offset.dx.abs() > @@ -102,9 +112,6 @@ class IndexStackDragCardDemoPageState childWhenDragging: Container(), feedback: getCardItem(i, dataList[i]), child: getCardItem(i, dataList[i])), - margin: EdgeInsets.only( - top: (i < 5) ? 10 * i.toDouble() : 40, - left: (i < 5) ? 8 * i.toDouble() : 32), )), )); } diff --git a/lib/widget/index_stack_drag_card_demo_page2.dart b/lib/widget/index_stack_drag_card_demo_page2.dart index ac8571b..a1b7d22 100644 --- a/lib/widget/index_stack_drag_card_demo_page2.dart +++ b/lib/widget/index_stack_drag_card_demo_page2.dart @@ -1,7 +1,10 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/physics.dart'; class IndexStackDragCardDemoPage2 extends StatefulWidget { + const IndexStackDragCardDemoPage2({super.key}); + @override _IndexStackDragCardDemoPage2State createState() => _IndexStackDragCardDemoPage2State(); @@ -21,8 +24,8 @@ class _IndexStackDragCardDemoPage2State setState(() { dataList.removeAt(index); }); - if (dataList.length == 0) { - Future.delayed(Duration(seconds: 0), () { + if (dataList.isEmpty) { + Future.delayed(const Duration(seconds: 0), () { setState(() { dataList = getDataList(); }); @@ -34,7 +37,7 @@ class _IndexStackDragCardDemoPage2State Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text('A draggable card!'), + title: const Text('A draggable card!'), ), body: Stack( children: getCardList(), @@ -72,7 +75,9 @@ class _IndexStackDragCardDemoPage2State getCardItem(index, data) { return GestureDetector( onTap: () { - print("###### ${data.name}"); + if (kDebugMode) { + print("###### ${data.name}"); + } }, child: Card( elevation: 8.0, @@ -83,7 +88,7 @@ class _IndexStackDragCardDemoPage2State children: [ Container( decoration: BoxDecoration( - borderRadius: BorderRadius.only( + borderRadius: const BorderRadius.only( topLeft: Radius.circular(20.0), topRight: Radius.circular(20.0)), image: DecorationImage( @@ -93,10 +98,10 @@ class _IndexStackDragCardDemoPage2State width: 300.0, ), Container( - padding: EdgeInsets.symmetric(vertical: 10), + padding: const EdgeInsets.symmetric(vertical: 10), child: Text( data.name, - style: TextStyle( + style: const TextStyle( fontSize: 18.0, color: Colors.blue, ), @@ -113,7 +118,7 @@ class DraggableCard extends StatefulWidget { final ValueChanged? removeCall; final int? index; - DraggableCard({this.child, this.removeCall, this.index}); + const DraggableCard({super.key, this.child, this.removeCall, this.index}); @override _DraggableCardState createState() => _DraggableCardState(); @@ -154,7 +159,7 @@ class _DraggableCardState extends State void initState() { super.initState(); _controller = AnimationController(vsync: this) - ..duration = Duration(microseconds: 500); + ..duration = const Duration(microseconds: 500); _controller.addListener(() { setState(() { @@ -177,7 +182,9 @@ class _DraggableCardState extends State _controller.stop(); }, onPanUpdate: (details) { - print("#### ${details.localPosition}"); + if (kDebugMode) { + print("#### ${details.localPosition}"); + } ///往下斜着拖 if ((details.localPosition.dx.abs() > diff --git a/lib/widget/input_bottom_demo_page.dart b/lib/widget/input_bottom_demo_page.dart index d84a660..8bb35f1 100644 --- a/lib/widget/input_bottom_demo_page.dart +++ b/lib/widget/input_bottom_demo_page.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; class InputBottomDemoPage extends StatefulWidget { + const InputBottomDemoPage({super.key}); + @override _InputBottomDemoPageState createState() => _InputBottomDemoPageState(); } @@ -8,7 +10,7 @@ class InputBottomDemoPage extends StatefulWidget { class _InputBottomDemoPageState extends State { bool isKeyboardShowing = false; - TextEditingController textEditingController = new TextEditingController(); + TextEditingController textEditingController = TextEditingController(); @override void didChangeDependencies() { @@ -26,68 +28,66 @@ class _InputBottomDemoPageState extends State { }, content: Scaffold( appBar: AppBar( - title: new Text("KeyBoardDemoPage"), + title: const Text("KeyBoardDemoPage"), ), - body: new GestureDetector( + body: GestureDetector( ///透明可以触摸 behavior: HitTestBehavior.translucent, onTap: () { /// 触摸收起键盘 - FocusScope.of(context).requestFocus(new FocusNode()); + FocusScope.of(context).requestFocus(FocusNode()); }, - child: new SafeArea( - child: Container( - child: new Stack( - fit: StackFit.expand, - children: [ - new Align( - alignment: Alignment.center, - child: - new Text("测试,测试,测试,测试,测试,测试,测试,测试,测试,测试,测试,测试,测试,测试,测试"), - ), - new Align( - alignment: Alignment.bottomCenter, - child: new Container( - width: MediaQuery.sizeOf(context).width, - child: new Column( - mainAxisSize: MainAxisSize.min, - children: [ - new Container( - width: MediaQuery.sizeOf(context).width, - padding: EdgeInsets.symmetric(horizontal: 10), - decoration: BoxDecoration( - border: Border.all(color: Colors.blueAccent)), - child: TextField( - decoration: InputDecoration( - hintText: "请输入", - enabledBorder: UnderlineInputBorder( - borderSide: BorderSide(width: 0)), - focusedBorder: UnderlineInputBorder( - borderSide: BorderSide(width: 0)), - disabledBorder: UnderlineInputBorder( - borderSide: BorderSide(width: 0)), - border: UnderlineInputBorder( - borderSide: BorderSide(width: 0))), - controller: textEditingController, - ), - ), - Visibility( - visible: isKeyboardShowing, - child: new Container( - alignment: Alignment.center, - color: Colors.grey, - height: 40, + child: SafeArea( + child: Stack( + fit: StackFit.expand, + children: [ + const Align( + alignment: Alignment.center, + child: + Text("测试,测试,测试,测试,测试,测试,测试,测试,测试,测试,测试,测试,测试,测试,测试"), + ), + Align( + alignment: Alignment.bottomCenter, + child: SizedBox( + width: MediaQuery.sizeOf(context).width, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( width: MediaQuery.sizeOf(context).width, - child: new Text("bottom bar"), + padding: const EdgeInsets.symmetric(horizontal: 10), + decoration: BoxDecoration( + border: Border.all(color: Colors.blueAccent)), + child: TextField( + decoration: const InputDecoration( + hintText: "请输入", + enabledBorder: UnderlineInputBorder( + borderSide: BorderSide(width: 0)), + focusedBorder: UnderlineInputBorder( + borderSide: BorderSide(width: 0)), + disabledBorder: UnderlineInputBorder( + borderSide: BorderSide(width: 0)), + border: UnderlineInputBorder( + borderSide: BorderSide(width: 0))), + controller: textEditingController, + ), + ), + Visibility( + visible: isKeyboardShowing, + child: Container( + alignment: Alignment.center, + color: Colors.grey, + height: 40, + width: MediaQuery.sizeOf(context).width, + child: const Text("bottom bar"), + ), ), - ), - ], + ], + ), ), ), - ), - ], - ), - )), + ], + )), ), ), ); @@ -102,7 +102,7 @@ class KeyboardDetector extends StatefulWidget { final Widget content; - KeyboardDetector({this.keyboardShowCallback, required this.content}); + const KeyboardDetector({super.key, this.keyboardShowCallback, required this.content}); @override _KeyboardDetectorState createState() => _KeyboardDetectorState(); diff --git a/lib/widget/juejin_3d_box_logo_demo_page.dart b/lib/widget/juejin_3d_box_logo_demo_page.dart index af238be..4cbfd8c 100644 --- a/lib/widget/juejin_3d_box_logo_demo_page.dart +++ b/lib/widget/juejin_3d_box_logo_demo_page.dart @@ -4,23 +4,23 @@ import 'package:flutter/material.dart'; import 'package:zflutter/zflutter.dart'; class JueJin3DBoxLogoDemoPage extends StatefulWidget { - const JueJin3DBoxLogoDemoPage({Key? key}) : super(key: key); + const JueJin3DBoxLogoDemoPage({super.key}); @override State createState() => _JueJin3DBoxLogoDemoPageState(); } class _JueJin3DBoxLogoDemoPageState extends State { - Color color = Color(0xFF1E80FF); - Color colorLight = Color(0xFF1E8FFF); - Color colorDeep = Color(0xA11E38FF); + Color color = const Color(0xFF1E80FF); + Color colorLight = const Color(0xFF1E8FFF); + Color colorDeep = const Color(0xA11E38FF); renderBottom() { return [ ZPositioned( - rotate: ZVector.only(z: pi * 0.28), + rotate: const ZVector.only(z: pi * 0.28), child: ZPositioned( - translate: ZVector(100, 100, 0), + translate: const ZVector(100, 100, 0), child: ZBoxToBoxAdapter( height: 153, width: 30, @@ -39,9 +39,9 @@ class _JueJin3DBoxLogoDemoPageState extends State { ), ), ZPositioned( - rotate: ZVector.only(z: -pi * 0.28), + rotate: const ZVector.only(z: -pi * 0.28), child: ZPositioned( - translate: ZVector(-0, 100, 0), + translate: const ZVector(-0, 100, 0), child: ZBoxToBoxAdapter( height: 153, width: 30, @@ -65,9 +65,9 @@ class _JueJin3DBoxLogoDemoPageState extends State { renderMiddle() { return [ ZPositioned( - rotate: ZVector.only(z: pi * 0.28), + rotate: const ZVector.only(z: pi * 0.28), child: ZPositioned( - translate: ZVector(80, 40, 0), + translate: const ZVector(80, 40, 0), child: ZBoxToBoxAdapter( height: 100, width: 30, @@ -86,9 +86,9 @@ class _JueJin3DBoxLogoDemoPageState extends State { ), ), ZPositioned( - rotate: ZVector.only(z: -pi * 0.28), + rotate: const ZVector.only(z: -pi * 0.28), child: ZPositioned( - translate: ZVector(20, 40, 0), + translate: const ZVector(20, 40, 0), child: ZBoxToBoxAdapter( height: 100, width: 30, @@ -114,9 +114,9 @@ class _JueJin3DBoxLogoDemoPageState extends State { renderTop() { return [ ZPositioned( - rotate: ZVector.only(z: -pi / 4), + rotate: const ZVector.only(z: -pi / 4), child: ZPositioned( - translate: ZVector(50, -30, 0), + translate: const ZVector(50, -30, 0), child: ZBoxToBoxAdapter( height: 40, width: 40, @@ -147,7 +147,7 @@ class _JueJin3DBoxLogoDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("JueJin3DBoxLogoDemoPage"), + title: const Text("JueJin3DBoxLogoDemoPage"), ), body: Center( child: ZDragDetector(builder: (context, controller) { @@ -157,7 +157,7 @@ class _JueJin3DBoxLogoDemoPageState extends State { ZPositioned( rotate: controller.rotate, child: ZPositioned( - translate: ZVector.only(x: -40), + translate: const ZVector.only(x: -40), child: ZGroup( children: [ ...renderBottom(), diff --git a/lib/widget/juejin_3d_logo_demo_page.dart b/lib/widget/juejin_3d_logo_demo_page.dart index 16ebc71..b5cf525 100644 --- a/lib/widget/juejin_3d_logo_demo_page.dart +++ b/lib/widget/juejin_3d_logo_demo_page.dart @@ -2,7 +2,7 @@ import 'package:flutter/material.dart'; import 'package:zflutter/zflutter.dart'; class JueJin3DLogoDemoPage extends StatefulWidget { - const JueJin3DLogoDemoPage({Key? key}) : super(key: key); + const JueJin3DLogoDemoPage({super.key}); @override State createState() => _JueJin3DLogoDemoPageState(); @@ -13,7 +13,7 @@ class _JueJin3DLogoDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("JueJin3DLogoDemoPage"), + title: const Text("JueJin3DLogoDemoPage"), ), body: Center( child: ZDragDetector(builder: (context, controller) { @@ -25,58 +25,58 @@ class _JueJin3DLogoDemoPageState extends State { child: ZGroup( children: [ ZPositioned( - translate: ZVector(-17.5865, -23.2854 / 2, 0), + translate: const ZVector(-17.5865, -23.2854 / 2, 0), child: ZShape( - color: Color(0xFF1E80FF), + color: const Color(0xFF1E80FF), stroke: 2, fill: true, path: [ - ZMove.vector(ZVector(17.5872, 6.77268, 0)), - ZLine.vector(ZVector(21.823, 3.40505, 0)), - ZLine.vector(ZVector(17.58723, 0.00748237, 0)), - ZLine.vector(ZVector(17.5835, 0, 0)), - ZLine.vector(ZVector(13.3552, 3.39757, 0)), - ZLine.vector(ZVector(17.5835, 6.76894, 0)), - ZLine.vector(ZVector(17.5872, 6.77268, 0)), + const ZMove.vector(ZVector(17.5872, 6.77268, 0)), + ZLine.vector(const ZVector(21.823, 3.40505, 0)), + ZLine.vector(const ZVector(17.58723, 0.00748237, 0)), + ZLine.vector(const ZVector(17.5835, 0, 0)), + ZLine.vector(const ZVector(13.3552, 3.39757, 0)), + ZLine.vector(const ZVector(17.5835, 6.76894, 0)), + ZLine.vector(const ZVector(17.5872, 6.77268, 0)), ], ), ), ZPositioned( - translate: ZVector(-17.5865, -23.2854 / 2, 0), + translate: const ZVector(-17.5865, -23.2854 / 2, 0), child: ZShape( - color: Color(0xFF1E80FF), + color: const Color(0xFF1E80FF), stroke: 2, fill: true, path: [ - ZMove.vector(ZVector(17.5865, 17.3955, 0)), - ZLine.vector(ZVector(28.5163, 8.77432, 0)), - ZLine.vector(ZVector(25.5528, 6.39453, 0)), - ZLine.vector(ZVector(17.5902, 12.6808, 0)), - ZLine.vector(ZVector(17.5865, 12.6808, 0)), - ZLine.vector(ZVector(9.62018, 6.40201, 0)), - ZLine.vector(ZVector(6.6604, 8.78181, 0)), - ZLine.vector(ZVector(17.5828, 17.39928, 0)), - ZLine.vector(ZVector(17.5865, 17.3955, 0)), + const ZMove.vector(ZVector(17.5865, 17.3955, 0)), + ZLine.vector(const ZVector(28.5163, 8.77432, 0)), + ZLine.vector(const ZVector(25.5528, 6.39453, 0)), + ZLine.vector(const ZVector(17.5902, 12.6808, 0)), + ZLine.vector(const ZVector(17.5865, 12.6808, 0)), + ZLine.vector(const ZVector(9.62018, 6.40201, 0)), + ZLine.vector(const ZVector(6.6604, 8.78181, 0)), + ZLine.vector(const ZVector(17.5828, 17.39928, 0)), + ZLine.vector(const ZVector(17.5865, 17.3955, 0)), ], ), ), ZPositioned( - translate: ZVector(-17.5865, -23.2854 / 2, 0), + translate: const ZVector(-17.5865, -23.2854 / 2, 0), child: ZShape( - color: Color(0xFF1E80FF), + color: const Color(0xFF1E80FF), stroke: 2, fill: true, path: [ - ZMove.vector(ZVector(17.5865, 23.2854, 0)), - ZLine.vector(ZVector(17.5828, 23.2891, 0)), - ZLine.vector(ZVector(2.95977, 11.7531, 0)), - ZLine.vector(ZVector(0, 14.1291, 0)), - ZLine.vector(ZVector(0.284376, 14.3574, 0)), - ZLine.vector(ZVector(17.5865, 28, 0)), - ZLine.vector(ZVector(28.5238, 19.3752, 0)), - ZLine.vector(ZVector(35.1768, 14.12542, 0)), - ZLine.vector(ZVector(32.2133, 11.7456, 0)), - ZLine.vector(ZVector(17.5865, 23.2854, 0)), + const ZMove.vector(ZVector(17.5865, 23.2854, 0)), + ZLine.vector(const ZVector(17.5828, 23.2891, 0)), + ZLine.vector(const ZVector(2.95977, 11.7531, 0)), + ZLine.vector(const ZVector(0, 14.1291, 0)), + ZLine.vector(const ZVector(0.284376, 14.3574, 0)), + ZLine.vector(const ZVector(17.5865, 28, 0)), + ZLine.vector(const ZVector(28.5238, 19.3752, 0)), + ZLine.vector(const ZVector(35.1768, 14.12542, 0)), + ZLine.vector(const ZVector(32.2133, 11.7456, 0)), + ZLine.vector(const ZVector(17.5865, 23.2854, 0)), ], ), ), diff --git a/lib/widget/keyboard_demo_page.dart b/lib/widget/keyboard_demo_page.dart index cd80121..416125b 100644 --- a/lib/widget/keyboard_demo_page.dart +++ b/lib/widget/keyboard_demo_page.dart @@ -3,6 +3,8 @@ import 'package:flutter/material.dart'; ///键盘相关Demo ///键盘是否弹起等 class KeyBoardDemoPage extends StatefulWidget { + const KeyBoardDemoPage({super.key}); + @override _KeyBoardDemoPageState createState() => _KeyBoardDemoPageState(); } @@ -10,7 +12,7 @@ class KeyBoardDemoPage extends StatefulWidget { class _KeyBoardDemoPageState extends State { bool isKeyboardShowing = false; - final FocusNode _focusNode = new FocusNode(); + final FocusNode _focusNode = FocusNode(); @override Widget build(BuildContext context) { @@ -24,61 +26,59 @@ class _KeyBoardDemoPageState extends State { }, content: Scaffold( appBar: AppBar( - title: new Text("KeyBoardDemoPage"), + title: const Text("KeyBoardDemoPage"), ), - body: new GestureDetector( + body: GestureDetector( ///透明可以触摸 behavior: HitTestBehavior.translucent, onTap: () { /// 触摸收起键盘 - FocusScope.of(context).requestFocus(new FocusNode()); + FocusScope.of(context).requestFocus(FocusNode()); }, - child: Container( - child: Column( - mainAxisSize: MainAxisSize.max, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - new Expanded( - child: new Container( - alignment: Alignment.center, - child: Text( - isKeyboardShowing ? "键盘弹起" : "键盘未弹起", - style: TextStyle( - color: isKeyboardShowing - ? Colors.redAccent - : Colors.greenAccent), - ), + child: Column( + mainAxisSize: MainAxisSize.max, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + flex: 2, + child: Container( + alignment: Alignment.center, + child: Text( + isKeyboardShowing ? "键盘弹起" : "键盘未弹起", + style: TextStyle( + color: isKeyboardShowing + ? Colors.redAccent + : Colors.greenAccent), ), - flex: 2, ), - new Expanded( - child: new Center( - child: new TextButton( - onPressed: () { - if (!isKeyboardShowing) { - /// 触摸收起键盘 - FocusScope.of(context).requestFocus(_focusNode); - } - }, - child: new Text("弹出键盘"), - ), + ), + Expanded( + child: Center( + child: TextButton( + onPressed: () { + if (!isKeyboardShowing) { + /// 触摸收起键盘 + FocusScope.of(context).requestFocus(_focusNode); + } + }, + child: const Text("弹出键盘"), ), ), - new Expanded( - flex: 2, - child: new Container( - margin: EdgeInsets.symmetric(horizontal: 10), - child: new TextField( - focusNode: _focusNode, - maxLines: 7, - minLines: 1, - decoration: - const InputDecoration(border: OutlineInputBorder()), - ), + ), + Expanded( + flex: 2, + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 10), + child: TextField( + focusNode: _focusNode, + maxLines: 7, + minLines: 1, + decoration: + const InputDecoration(border: OutlineInputBorder()), ), - ) - ], - ), + ), + ) + ], ), ), ), @@ -94,7 +94,7 @@ class KeyboardDetector extends StatefulWidget { final Widget content; - KeyboardDetector({this.keyboardShowCallback, required this.content}); + const KeyboardDetector({super.key, this.keyboardShowCallback, required this.content}); @override _KeyboardDetectorState createState() => _KeyboardDetectorState(); diff --git a/lib/widget/link_sliver/link_flexible_space_bar.dart b/lib/widget/link_sliver/link_flexible_space_bar.dart index bffe4f1..93f4fcd 100644 --- a/lib/widget/link_sliver/link_flexible_space_bar.dart +++ b/lib/widget/link_sliver/link_flexible_space_bar.dart @@ -4,7 +4,7 @@ import 'package:flutter/material.dart'; class LinkFlexibleSpaceBar extends StatefulWidget { const LinkFlexibleSpaceBar({ - Key? key, + super.key, this.title, this.background, this.centerTitle, @@ -13,7 +13,7 @@ class LinkFlexibleSpaceBar extends StatefulWidget { this.titlePadding, this.collapseMode = CollapseMode.parallax, this.stretchModes = const [StretchMode.zoomBackground], - }) : super(key: key); + }); final Widget? title; @@ -123,12 +123,12 @@ class _LinkFlexibleSpaceBarState extends State { (constraints.maxHeight - settings.maxExtent) / 10; children.add(Positioned.fill( child: BackdropFilter( - child: Container( - color: Colors.transparent, - ), filter: ui.ImageFilter.blur( sigmaX: blurAmount, sigmaY: blurAmount, + ), + child: Container( + color: Colors.transparent, )))); } } @@ -193,8 +193,8 @@ class _LinkFlexibleSpaceBarState extends State { padding: padding, child: Column( children: [ - Spacer(), - new Row( + const Spacer(), + Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ Transform( @@ -208,13 +208,13 @@ class _LinkFlexibleSpaceBarState extends State { ), ), ), - Spacer(), + const Spacer(), Opacity( opacity: opacityValue, - child: new Container( + child: Container( width: 60, height: 60, - margin: EdgeInsets.only(right: 20, bottom: 20), + margin: const EdgeInsets.only(right: 20, bottom: 20), decoration: BoxDecoration( image: DecorationImage( image: AssetImage( @@ -223,19 +223,19 @@ class _LinkFlexibleSpaceBarState extends State { fit: BoxFit.cover, ), borderRadius: - BorderRadius.all(Radius.circular(30))), + const BorderRadius.all(Radius.circular(30))), ), ), ], ), Opacity( opacity: opacityValue, - child: Container( + child: SizedBox( height: 80 * scaleBottomValue, child: Column( children: [ - new Expanded( - child: new Row( + Expanded( + child: Row( children: widget.bottom ?? Container() as List, ), @@ -257,10 +257,10 @@ class _LinkFlexibleSpaceBarState extends State { renderItem() { return Expanded( - child: new Container( + child: Container( alignment: Alignment.centerLeft, - child: Center( - child: new Text( + child: const Center( + child: Text( "FFFF", style: TextStyle(fontSize: 18, color: Colors.white), ), diff --git a/lib/widget/link_sliver/link_sliver_demo_page.dart b/lib/widget/link_sliver/link_sliver_demo_page.dart index 216c470..f47d164 100644 --- a/lib/widget/link_sliver/link_sliver_demo_page.dart +++ b/lib/widget/link_sliver/link_sliver_demo_page.dart @@ -4,6 +4,8 @@ import 'package:gsy_flutter_demo/widget/link_sliver/link_flexible_space_bar.dart import 'link_sliver_header.dart'; class LinkSliverDemoPage extends StatefulWidget { + const LinkSliverDemoPage({super.key}); + @override _LinkSliverDemoPageState createState() => _LinkSliverDemoPageState(); } @@ -11,10 +13,10 @@ class LinkSliverDemoPage extends StatefulWidget { class _LinkSliverDemoPageState extends State { renderBottomItem() { return Expanded( - child: new Container( + child: Container( alignment: Alignment.centerLeft, - child: Center( - child: new Text( + child: const Center( + child: Text( "FFFF", style: TextStyle(fontSize: 18, color: Colors.white), ), @@ -26,77 +28,75 @@ class _LinkSliverDemoPageState extends State { @override Widget build(BuildContext context) { return Scaffold( - body: Container( - child: NestedScrollView( - headerSliverBuilder: (context, innerBoxIsScrolled) { - return [ - SliverAppBar( - automaticallyImplyLeading: false, - leading: Container(), - expandedHeight: 260.0, - flexibleSpace: LinkFlexibleSpaceBar( - centerTitle: false, - title: Container( - margin: EdgeInsets.only(left: 20, top: 30, bottom: 20), - child: new Text("GSY"), - ), - image: "static/gsy_cat.png", - bottom: List.generate(4, (index) { - return renderBottomItem(); - }), - titlePadding: EdgeInsets.all(0), + body: NestedScrollView( + headerSliverBuilder: (context, innerBoxIsScrolled) { + return [ + SliverAppBar( + automaticallyImplyLeading: false, + leading: Container(), + expandedHeight: 260.0, + flexibleSpace: LinkFlexibleSpaceBar( + centerTitle: false, + title: Container( + margin: const EdgeInsets.only(left: 20, top: 30, bottom: 20), + child: const Text("GSY"), ), - pinned: true, - actions: [ - IconButton( - icon: const Icon(Icons.settings_overscan), - tooltip: 'Add new entry', - onPressed: () {}, - ), - IconButton( - icon: const Icon(Icons.settings), - tooltip: 'Add new entry', - onPressed: () {}, - ), - ], + image: "static/gsy_cat.png", + bottom: List.generate(4, (index) { + return renderBottomItem(); + }), + titlePadding: const EdgeInsets.all(0), ), - ]; - }, - body: MediaQuery.removePadding( - removeTop: true, - context: context, - child: CustomScrollView( - ///回弹效果 - physics: const BouncingScrollPhysics( - parent: AlwaysScrollableScrollPhysics()), - slivers: [ - LinkSliverHeader( - initLayoutExtent: 60, - containerExtent: 120, - triggerPullDistance: 120, - pinned: false, + pinned: true, + actions: [ + IconButton( + icon: const Icon(Icons.settings_overscan), + tooltip: 'Add new entry', + onPressed: () {}, ), - - ///列表区域 - SliverSafeArea( - sliver: SliverList( - ///代理显示 - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - return Card( - child: new Container( - height: 60, - alignment: Alignment.centerLeft, - child: new Text("Item $index"), - ), - ); - }, - childCount: 100, - ), - ), + IconButton( + icon: const Icon(Icons.settings), + tooltip: 'Add new entry', + onPressed: () {}, ), ], ), + ]; + }, + body: MediaQuery.removePadding( + removeTop: true, + context: context, + child: CustomScrollView( + ///回弹效果 + physics: const BouncingScrollPhysics( + parent: AlwaysScrollableScrollPhysics()), + slivers: [ + const LinkSliverHeader( + initLayoutExtent: 60, + containerExtent: 120, + triggerPullDistance: 120, + pinned: false, + ), + + ///列表区域 + SliverSafeArea( + sliver: SliverList( + ///代理显示 + delegate: SliverChildBuilderDelegate( + (BuildContext context, int index) { + return Card( + child: Container( + height: 60, + alignment: Alignment.centerLeft, + child: Text("Item $index"), + ), + ); + }, + childCount: 100, + ), + ), + ), + ], ), ), ), diff --git a/lib/widget/link_sliver/link_sliver_header.dart b/lib/widget/link_sliver/link_sliver_header.dart index d0993e3..be573ab 100644 --- a/lib/widget/link_sliver/link_sliver_header.dart +++ b/lib/widget/link_sliver/link_sliver_header.dart @@ -5,14 +5,12 @@ import 'package:flutter/rendering.dart'; class _LinkSliverHeader extends SingleChildRenderObjectWidget { const _LinkSliverHeader({ - Key? key, this.containerLayoutExtent = 0.0, this.initLayoutExtent = 0.0, this.hasLayoutExtent = false, this.pinned = false, - Widget? child, - }) : assert(containerLayoutExtent >= 0.0), - super(key: key, child: child); + super.child, + }) : assert(containerLayoutExtent >= 0.0); final double initLayoutExtent; final double containerLayoutExtent; @@ -223,7 +221,7 @@ typedef ContainerBuilder = Widget Function( class LinkSliverHeader extends StatefulWidget { const LinkSliverHeader({ - Key? key, + super.key, this.triggerPullDistance = _defaultTriggerPullDistance, this.containerExtent = _defaultcontainerExtent, this.initLayoutExtent = 0, @@ -234,8 +232,7 @@ class LinkSliverHeader extends StatefulWidget { assert( triggerPullDistance >= containerExtent, 'The container cannot take more space in its final state ' - 'than the amount initially created by overscrolling.'), - super(key: key); + 'than the amount initially created by overscrolling.'); final double triggerPullDistance; @@ -258,15 +255,14 @@ class LinkSliverHeader extends StatefulWidget { ) { return Stack( children: [ - new Container( + Container( color: Colors.blue, - padding: EdgeInsets.symmetric(horizontal: 30), + padding: const EdgeInsets.symmetric(horizontal: 30), child: InkWell( onTap: () { - print("FFFF"); }, - child: new Container( - decoration: BoxDecoration( + child: Container( + decoration: const BoxDecoration( borderRadius: BorderRadius.only( topLeft: Radius.circular(10), topRight: Radius.circular(10), diff --git a/lib/widget/list_anim/header_appbar.dart b/lib/widget/list_anim/header_appbar.dart index cfbbf07..b8aa464 100644 --- a/lib/widget/list_anim/header_appbar.dart +++ b/lib/widget/list_anim/header_appbar.dart @@ -4,7 +4,7 @@ class HeaderAppBar extends StatelessWidget { final int alphaBg; final bool showStickItem; - HeaderAppBar({this.alphaBg = 0, this.showStickItem = false}); + const HeaderAppBar({super.key, this.alphaBg = 0, this.showStickItem = false}); @override Widget build(BuildContext context) { @@ -20,50 +20,50 @@ class HeaderAppBar extends StatelessWidget { var color = Theme.of(context).primaryColor.withAlpha(alphaBg); - return new Material( + return Material( color: Colors.transparent, - child: new Container( + child: Container( alignment: Alignment.centerLeft, height: containerHeight, - child: new Column( + child: Column( mainAxisSize: MainAxisSize.max, children: [ ///撑满状态栏颜色 - new Container( + Container( height: statusBarHeight, color: color, ), - new Container( + Container( color: color, height: kToolbarHeight, - child: new Row( + child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - new Container( + Container( width: 36, height: 36, alignment: Alignment.center, - margin: EdgeInsets.only(right: 10, left: 10), + margin: const EdgeInsets.only(right: 10, left: 10), decoration: BoxDecoration( color: Colors.white.withAlpha(125), - borderRadius: BorderRadius.all(Radius.circular(18))), + borderRadius: const BorderRadius.all(Radius.circular(18))), child: InkWell( onTap: () { Navigator.of(context).pop(); }, - child: Icon( + child: const Icon( Icons.arrow_back_ios, color: Colors.white, ), ), ), - new Expanded( - child: new Container( + Expanded( + child: Container( height: kToolbarHeight - 15, - margin: EdgeInsets.only(right: 20, left: 20), + margin: const EdgeInsets.only(right: 20, left: 20), decoration: BoxDecoration( color: Colors.white.withAlpha(125), - borderRadius: BorderRadius.all(Radius.circular(10))), + borderRadius: const BorderRadius.all(Radius.circular(10))), ), ), ], @@ -73,23 +73,23 @@ class HeaderAppBar extends StatelessWidget { ? Container( alignment: Alignment.centerLeft, width: MediaQuery.sizeOf(context).width, - padding: EdgeInsets.only(left: 10), + padding: const EdgeInsets.only(left: 10), height: reactHeight, color: Colors.amber, - child: new Row( + child: const Row( children: [ - new Icon(Icons.ac_unit, color: Colors.white, size: 13), - new SizedBox( + Icon(Icons.ac_unit, color: Colors.white, size: 13), + SizedBox( width: 10, ), - new Text( + Text( "StickText", style: TextStyle(color: Colors.white), ), ], ), ) - : new Container() + : Container() ], ), ), diff --git a/lib/widget/list_anim/list_anim_demo_page.dart b/lib/widget/list_anim/list_anim_demo_page.dart index 49d1e51..7b8d9f1 100644 --- a/lib/widget/list_anim/list_anim_demo_page.dart +++ b/lib/widget/list_anim/list_anim_demo_page.dart @@ -4,6 +4,8 @@ import 'package:flutter/material.dart'; import 'package:gsy_flutter_demo/widget/list_anim/header_appbar.dart'; class ListAnimDemoPage extends StatefulWidget { + const ListAnimDemoPage({super.key}); + @override _ListAnimDemoPageState createState() => _ListAnimDemoPageState(); } @@ -58,30 +60,30 @@ class _ListAnimDemoPageState extends State { return Container( alignment: Alignment.topCenter, height: headerHeight, - child: new Stack( + child: Stack( children: [ - new Image.asset( + Image.asset( "static/gsy_cat.png", fit: BoxFit.cover, width: MediaQuery.sizeOf(context).width, height: headerHeight - headerRectMargin, ), - new Align( + Align( alignment: Alignment.bottomCenter, child: Container( height: headerRectHeight, color: Colors.amber, margin: EdgeInsets.only(left: marginEdge, right: marginEdge), - padding: EdgeInsets.symmetric(horizontal: 10), - child: new Row( + padding: const EdgeInsets.symmetric(horizontal: 10), + child: Row( mainAxisSize: MainAxisSize.max, children: [ - new Text( + const Text( "StickText", style: TextStyle(color: Colors.white, fontSize: 20), ), - new Expanded(child: new Container()), - new Icon( + Expanded(child: Container()), + const Icon( Icons.ac_unit, color: Colors.white, ) @@ -113,7 +115,7 @@ class _ListAnimDemoPageState extends State { @override Widget build(BuildContext context) { - return new Stack( + return Stack( children: [ Scaffold( ///去除 SafeArea 的 padding @@ -123,30 +125,28 @@ class _ListAnimDemoPageState extends State { removeTop: true, removeRight: true, removeBottom: true, - child: Container( - child: new NotificationListener( - onNotification: (ScrollNotification notification) { - if (notification is ScrollUpdateNotification) { - _handleScrollUpdateNotification(notification); + child: NotificationListener( + onNotification: (ScrollNotification notification) { + if (notification is ScrollUpdateNotification) { + _handleScrollUpdateNotification(notification); + } + return false; + }, + child: ListView.builder( + physics: const AlwaysScrollableScrollPhysics(), + itemBuilder: (context, index) { + if (index == 0) { + return _buildHeader(); } - return false; + return Card( + child: Container( + height: 60, + alignment: Alignment.centerLeft, + child: Text("Item ${[index]} FFFFF"), + ), + ); }, - child: new ListView.builder( - physics: const AlwaysScrollableScrollPhysics(), - itemBuilder: (context, index) { - if (index == 0) { - return _buildHeader(); - } - return Card( - child: new Container( - height: 60, - alignment: Alignment.centerLeft, - child: new Text("Item ${[index]} FFFFF"), - ), - ); - }, - itemCount: 100, - ), + itemCount: 100, ), ), ), diff --git a/lib/widget/list_anim_2/header_appbar.dart b/lib/widget/list_anim_2/header_appbar.dart index 39017fd..66fded7 100644 --- a/lib/widget/list_anim_2/header_appbar.dart +++ b/lib/widget/list_anim_2/header_appbar.dart @@ -4,7 +4,7 @@ class HeaderAppBar2 extends StatelessWidget { final int alphaBg; final bool showStickItem; - HeaderAppBar2({this.alphaBg = 0, this.showStickItem = false}); + const HeaderAppBar2({super.key, this.alphaBg = 0, this.showStickItem = false}); @override Widget build(BuildContext context) { @@ -20,30 +20,31 @@ class HeaderAppBar2 extends StatelessWidget { var color = Theme.of(context).primaryColor.withAlpha(alphaBg); - return new Material( + return Material( color: Colors.transparent, - child: new Container( + child: Container( alignment: Alignment.centerLeft, height: containerHeight, - child: new Stack( + child: Stack( children: [ - new Container( + Container( margin: EdgeInsets.only(top: statusBarHeight + kToolbarHeight), child: AnimatedSwitcher( - switchInCurve: Cubic(0.4, 0.0, 0.2, 1.0), - switchOutCurve: Cubic(1.0, 0.1, 1.0, 0.1), + switchInCurve: const Cubic(0.4, 0.0, 0.2, 1.0), + switchOutCurve: const Cubic(1.0, 0.1, 1.0, 0.1), transitionBuilder: (child, anim) { ///不同状态显示不同动画 - if (showStickItem) + if (showStickItem) { return SlideTransition( - child: child, position: Tween( - begin: Offset(0.0, -0.5), - end: Offset(0.0, 0.0), - ).animate(anim)); + begin: const Offset(0.0, -0.5), + end: const Offset(0.0, 0.0), + ).animate(anim), + child: child); + } return FadeTransition( - child: child, opacity: anim, + child: child, ); }, duration: Duration(milliseconds: showStickItem ? 500 : 1), @@ -52,68 +53,68 @@ class HeaderAppBar2 extends StatelessWidget { alignment: Alignment.centerLeft, width: MediaQuery.sizeOf(context).width, height: reactHeight, - key: ValueKey("stickItem"), + key: const ValueKey("stickItem"), color: Colors.amber, - child: new Row( + child: const Row( children: [ - new Icon(Icons.ac_unit, + Icon(Icons.ac_unit, color: Colors.white, size: 13), - new SizedBox( + SizedBox( width: 10, ), - new Text( + Text( "StickText", style: TextStyle(color: Colors.white), ), ], ), ) - : new Container( - key: ValueKey("hideItem"), + : Container( + key: const ValueKey("hideItem"), ), ), ), - new Column( + Column( mainAxisSize: MainAxisSize.max, children: [ ///撑满状态栏颜色 - new Container( + Container( height: statusBarHeight, color: color, ), - new Container( + Container( color: color, height: kToolbarHeight, - child: new Row( + child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - new Container( + Container( width: 36, height: 36, alignment: Alignment.center, - margin: EdgeInsets.only(right: 10, left: 10), + margin: const EdgeInsets.only(right: 10, left: 10), decoration: BoxDecoration( color: Colors.white.withAlpha(125), borderRadius: - BorderRadius.all(Radius.circular(18))), + const BorderRadius.all(Radius.circular(18))), child: InkWell( onTap: () { Navigator.of(context).pop(); }, - child: Icon( + child: const Icon( Icons.arrow_back_ios, color: Colors.white, ), ), ), - new Expanded( - child: new Container( + Expanded( + child: Container( height: kToolbarHeight - 15, - margin: EdgeInsets.only(right: 20, left: 20), + margin: const EdgeInsets.only(right: 20, left: 20), decoration: BoxDecoration( color: Colors.white.withAlpha(125), borderRadius: - BorderRadius.all(Radius.circular(10))), + const BorderRadius.all(Radius.circular(10))), ), ), ], diff --git a/lib/widget/list_anim_2/list_anim_demo_page.dart b/lib/widget/list_anim_2/list_anim_demo_page.dart index 2ff8126..7060fd9 100644 --- a/lib/widget/list_anim_2/list_anim_demo_page.dart +++ b/lib/widget/list_anim_2/list_anim_demo_page.dart @@ -4,6 +4,8 @@ import 'package:flutter/material.dart'; import 'package:gsy_flutter_demo/widget/list_anim_2/header_appbar.dart'; class ListAnimDemoPage2 extends StatefulWidget { + const ListAnimDemoPage2({super.key}); + @override _ListAnimDemoPageState2 createState() => _ListAnimDemoPageState2(); } @@ -56,30 +58,30 @@ class _ListAnimDemoPageState2 extends State { return Container( alignment: Alignment.topCenter, height: headerHeight, - child: new Stack( + child: Stack( children: [ - new Image.asset( + Image.asset( "static/gsy_cat.png", fit: BoxFit.cover, width: MediaQuery.sizeOf(context).width, height: headerHeight - headerRectMargin, ), - new Align( + Align( alignment: Alignment.bottomCenter, child: Container( height: headerRectHeight, color: Colors.amber, - margin: EdgeInsets.only(left: 10, right: 10), - padding: EdgeInsets.symmetric(horizontal: 10), - child: new Row( + margin: const EdgeInsets.only(left: 10, right: 10), + padding: const EdgeInsets.symmetric(horizontal: 10), + child: Row( mainAxisSize: MainAxisSize.max, children: [ - new Text( + const Text( "StickText", style: TextStyle(color: Colors.white, fontSize: 20), ), - new Expanded(child: new Container()), - new Icon( + Expanded(child: Container()), + const Icon( Icons.ac_unit, color: Colors.white, ) @@ -111,7 +113,7 @@ class _ListAnimDemoPageState2 extends State { @override Widget build(BuildContext context) { - return new Stack( + return Stack( children: [ Scaffold( ///去除 SafeArea 的 padding @@ -121,30 +123,28 @@ class _ListAnimDemoPageState2 extends State { removeTop: true, removeRight: true, removeBottom: true, - child: Container( - child: new NotificationListener( - onNotification: (ScrollNotification notification) { - if (notification is ScrollUpdateNotification) { - _handleScrollUpdateNotification(notification); + child: NotificationListener( + onNotification: (ScrollNotification notification) { + if (notification is ScrollUpdateNotification) { + _handleScrollUpdateNotification(notification); + } + return false; + }, + child: ListView.builder( + physics: const AlwaysScrollableScrollPhysics(), + itemBuilder: (context, index) { + if (index == 0) { + return _buildHeader(); } - return false; + return Card( + child: Container( + height: 60, + alignment: Alignment.centerLeft, + child: Text("Item ${[index]} FFFFF"), + ), + ); }, - child: new ListView.builder( - physics: const AlwaysScrollableScrollPhysics(), - itemBuilder: (context, index) { - if (index == 0) { - return _buildHeader(); - } - return Card( - child: new Container( - height: 60, - alignment: Alignment.centerLeft, - child: new Text("Item ${[index]} FFFFF"), - ), - ); - }, - itemCount: 100, - ), + itemCount: 100, ), ), ), diff --git a/lib/widget/list_link_bottomsheet_demo_page.dart b/lib/widget/list_link_bottomsheet_demo_page.dart index 238ebb4..2dfb912 100644 --- a/lib/widget/list_link_bottomsheet_demo_page.dart +++ b/lib/widget/list_link_bottomsheet_demo_page.dart @@ -6,7 +6,7 @@ import 'dart:async'; ///列表简单联动 BottomSheet class ListLinkBottomSheetDemoPage extends StatefulWidget { - const ListLinkBottomSheetDemoPage({Key? key}) : super(key: key); + const ListLinkBottomSheetDemoPage({super.key}); @override State createState() => @@ -20,8 +20,8 @@ class _ListLinkBottomSheetDemoPageState ScrollController? _activeScrollController; Drag? _drag; Drag? _bottomSheetDrag; - GlobalKey<_LinkBottomSheetState> btKey = new GlobalKey(); - _BTController _btController = _BTController(); + GlobalKey<_LinkBottomSheetState> btKey = GlobalKey(); + final _BTController _btController = _BTController(); @override void initState() { @@ -43,13 +43,13 @@ class _ListLinkBottomSheetDemoPageState if (_listScrollController?.hasClients == true && _listScrollController?.position.context.storageContext != null) { ///获取 ListView 的 renderBox - final RenderBox? renderBox = _listScrollController + final RenderBox renderBox = _listScrollController ?.position.context.storageContext .findRenderObject() as RenderBox; ///判断触摸的位置是否在 ListView 内 ///不在范围内一般是因为 ListView 已经滑动上去了,坐标位置和触摸位置不一致 - if (renderBox?.paintBounds + if (renderBox.paintBounds .shift(renderBox.localToGlobal(Offset.zero)) .contains(details.globalPosition) == true) { @@ -118,7 +118,7 @@ class _ListLinkBottomSheetDemoPageState Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("ListLinkBottomSheetDemoPage"), + title: const Text("ListLinkBottomSheetDemoPage"), ), extendBody: true, body: RawGestureDetector( @@ -163,7 +163,7 @@ class _ListLinkBottomSheetDemoPageState )), Container( color: Colors.white, - child: Center( + child: const Center( child: Text( '纯粹背后占位', style: TextStyle(fontSize: 50), @@ -189,13 +189,11 @@ class _ListLinkBottomSheetDemoPageState }, onVerticalDragUpdate: (details) { if (_activeScrollController == _pageController) { - if (_bottomSheetDrag == null) { - _bottomSheetDrag = _pageController?.position.drag( + _bottomSheetDrag ??= _pageController?.position.drag( DragStartDetails( globalPosition: details.globalPosition, localPosition: details.localPosition), _disposeDrag); - } _bottomSheetDrag?.update(details); } }, @@ -234,7 +232,7 @@ class _KeepAliveListView extends StatefulWidget { final ScrollController? listScrollController; final int itemCount; - _KeepAliveListView({ + const _KeepAliveListView({ required this.listScrollController, required this.itemCount, }); @@ -288,7 +286,7 @@ class _LinkBottomSheet extends StatefulWidget { final void Function(DragEndDetails details)? onVerticalDragEnd; _LinkBottomSheet({ - Key? key, + super.key, required this.headerBar, required this.body, required this.controller, @@ -306,11 +304,10 @@ class _LinkBottomSheet extends StatefulWidget { this.onVerticalDragEnd, this.onVerticalDragUpdate, }) : assert(elevation >= 0.0), - assert(minHeight >= 0.0), - super(key: key) { - this.controller!.height = - this.showOnAppear ? this.maxHeight : this.minHeight; - this.controller!.config = smoothness; + assert(minHeight >= 0.0) { + controller!.height = + showOnAppear ? maxHeight : minHeight; + controller!.config = smoothness; } @override @@ -332,12 +329,13 @@ class _LinkBottomSheetState extends State<_LinkBottomSheet> { void onVerticalDragEnd(data, fromOuter) { _setUsersConfig(); - if (isDragDirectionUp! && widget.controller!.value) + if (isDragDirectionUp! && widget.controller!.value) { _show(); - else if (!isDragDirectionUp! && !widget.controller!.value) + } else if (!isDragDirectionUp! && !widget.controller!.value) { _hide(); - else + } else { widget.controller!.value = isDragDirectionUp!; + } if (!fromOuter) widget.onVerticalDragEnd?.call(data); } @@ -466,7 +464,7 @@ class _BTConfig { } class _BTController extends ValueNotifier { - BTStreamStatus _bloc = BTStreamStatus(); + final BTStreamStatus _bloc = BTStreamStatus(); double? _height; @@ -499,14 +497,14 @@ class _BTController extends ValueNotifier { } class BTStreamStatus { - StreamController _heightController = + final StreamController _heightController = StreamController.broadcast(); Stream get height => _heightController.stream; Sink get _heightSink => _heightController.sink; - StreamController _visibilityController = + final StreamController _visibilityController = StreamController.broadcast(); Stream get isOpen => _visibilityController.stream; diff --git a/lib/widget/matrix_custom_painter_page.dart b/lib/widget/matrix_custom_painter_page.dart index 7f97d13..9e3b047 100644 --- a/lib/widget/matrix_custom_painter_page.dart +++ b/lib/widget/matrix_custom_painter_page.dart @@ -4,6 +4,8 @@ import 'package:flutter/material.dart'; import 'package:matrix_gesture_detector/matrix_gesture_detector.dart'; class MatrixCustomPainterDemo extends StatefulWidget { + const MatrixCustomPainterDemo({super.key}); + @override _MatrixCustomPainterDemoState createState() => _MatrixCustomPainterDemoState(); } @@ -22,7 +24,7 @@ class _MatrixCustomPainterDemoState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text('MatrixCustomPainterDemo Demo'), + title: const Text('MatrixCustomPainterDemo Demo'), ), body: MatrixGestureDetector( onMatrixUpdate: (m, tm, sm, rm) => notifier!.value = m, @@ -77,7 +79,7 @@ class TestCustomPainter extends CustomPainter { for (int i = 0; i < 3; i++) { path.addRRect(rr.shift(offset * i.toDouble())); } - backgroundPaint.shader = LinearGradient( + backgroundPaint.shader = const LinearGradient( colors: [ Color(0xff000044), Color(0xff000022), @@ -90,10 +92,10 @@ class TestCustomPainter extends CustomPainter { canvas.drawPaint(backgroundPaint); - shapesPaint.color = Color(0xff880000); + shapesPaint.color = const Color(0xff880000); canvas.drawPath(path, shapesPaint); - shapesPaint.color = Color(0xffbb6600); + shapesPaint.color = const Color(0xffbb6600); Matrix4 inverted = Matrix4.zero(); inverted.copyInverse(notifier!.value); canvas.save(); @@ -101,7 +103,7 @@ class TestCustomPainter extends CustomPainter { canvas.drawPath(path, shapesPaint); canvas.restore(); - shapesPaint.color = Color(0xff008800); + shapesPaint.color = const Color(0xff008800); canvas.drawPath(path.transform(notifier!.value.storage), shapesPaint); paragraph.layout(ui.ParagraphConstraints(width: size.width - 64)); diff --git a/lib/widget/overflow_image_page.dart b/lib/widget/overflow_image_page.dart index bae8242..b7e90e2 100644 --- a/lib/widget/overflow_image_page.dart +++ b/lib/widget/overflow_image_page.dart @@ -2,14 +2,16 @@ import 'package:flutter/material.dart'; /// 圆角效果处理实现 class OverflowImagePage extends StatelessWidget { + const OverflowImagePage({super.key}); + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("OverflowImagePage"), + title: const Text("OverflowImagePage"), ), body: ListView.builder( - physics: ClampingScrollPhysics(), + physics: const ClampingScrollPhysics(), itemBuilder: (context, index) { ///第二个Item if (index == 1) { @@ -20,17 +22,17 @@ class OverflowImagePage extends StatelessWidget { } ///广告图 Item - return new Container( + return SizedBox( height: 100, child: OverflowBox( alignment: Alignment.center, + maxHeight: MediaQuery.sizeOf(context).height, child: Image( width: MediaQuery.sizeOf(context).width, height: MediaQuery.sizeOf(context).width * 220 / 247, - image: AssetImage("static/gsy_cat.png"), + image: const AssetImage("static/gsy_cat.png"), fit: BoxFit.fill, - ), - maxHeight: MediaQuery.sizeOf(context).height), + )), ); }, itemCount: 2, diff --git a/lib/widget/pageview_in_pageview_demo_page.dart b/lib/widget/pageview_in_pageview_demo_page.dart index f399823..da3518d 100644 --- a/lib/widget/pageview_in_pageview_demo_page.dart +++ b/lib/widget/pageview_in_pageview_demo_page.dart @@ -5,7 +5,7 @@ import 'package:flutter/rendering.dart'; //https://dartpad.dev/?id=abe26388e1f3a2ea0660fbd6089c6da5 class PageViewInPageViewDemoPage extends StatefulWidget { - const PageViewInPageViewDemoPage({Key? key}) : super(key: key); + const PageViewInPageViewDemoPage({super.key}); @override State createState() => @@ -98,7 +98,7 @@ class _PageViewInPageViewDemoPageState Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("PageViewInPageViewDemoPage"), + title: const Text("PageViewInPageViewDemoPage"), ), extendBody: true, body: PageView( @@ -107,9 +107,7 @@ class _PageViewInPageViewDemoPageState children: [ Column( children: [ - Container( - child: new Text("Inner PageView 1"), - ), + const Text("Inner PageView 1"), Expanded( child: NotificationListener( onNotification: (notification) { @@ -125,13 +123,13 @@ class _PageViewInPageViewDemoPageState isEnd = false; } }, - physics: ClampingScrollPhysics(), + physics: const ClampingScrollPhysics(), controller: _pageController3, children: [ KeepAliveWrapper( child: Container( color: Colors.purpleAccent, - child: Center( + child: const Center( child: Text("Inner PageView Item"), ), ), @@ -139,7 +137,7 @@ class _PageViewInPageViewDemoPageState KeepAliveWrapper( child: Container( color: Colors.teal, - child: Center( + child: const Center( child: Text("Inner PageView Item"), ), ), @@ -152,9 +150,7 @@ class _PageViewInPageViewDemoPageState ), Column( children: [ - Container( - child: new Text("Inner PageView 2"), - ), + const Text("Inner PageView 2"), Expanded( child: NotificationListener( onNotification: (notification) { @@ -163,13 +159,13 @@ class _PageViewInPageViewDemoPageState return false; }, child: PageView( - physics: ClampingScrollPhysics(), + physics: const ClampingScrollPhysics(), controller: _pageController2, children: [ KeepAliveWrapper( child: Container( color: Colors.greenAccent, - child: Center( + child: const Center( child: Text("Inner PageView Item"), ), ), @@ -177,7 +173,7 @@ class _PageViewInPageViewDemoPageState KeepAliveWrapper( child: Container( color: Colors.yellowAccent, - child: Center( + child: const Center( child: Text("Inner PageView Item"), ), ), @@ -190,7 +186,7 @@ class _PageViewInPageViewDemoPageState ), Container( color: Colors.blue, - child: Center( + child: const Center( child: Text("Outer PageView Item"), ), ), @@ -202,10 +198,10 @@ class _PageViewInPageViewDemoPageState class KeepAliveWrapper extends StatefulWidget { const KeepAliveWrapper({ - Key? key, + super.key, this.keepAlive = true, required this.child, - }) : super(key: key); + }); final bool keepAlive; final Widget child; diff --git a/lib/widget/particle/particle_model.dart b/lib/widget/particle/particle_model.dart index 6726dd3..9ec09b3 100644 --- a/lib/widget/particle/particle_model.dart +++ b/lib/widget/particle/particle_model.dart @@ -24,9 +24,9 @@ class ParticleModel { tween = MovieTween() ..tween(ParticleOffsetProps.x, startPosition.dx.tweenTo(endPosition.dx), - duration: Duration(milliseconds: 20)) + duration: const Duration(milliseconds: 20)) ..tween(ParticleOffsetProps.y, startPosition.dy.tweenTo(endPosition.dy), - duration: Duration(milliseconds: 20)); + duration: const Duration(milliseconds: 20)); duration = 3000.milliseconds + random.nextInt(6000).milliseconds; startTime = DateTime.now().duration(); @@ -34,7 +34,7 @@ class ParticleModel { } void _shuffle() { - startTime -= (this.random.nextDouble() * duration.inMilliseconds) + startTime -= (random.nextDouble() * duration.inMilliseconds) .round() .milliseconds; } diff --git a/lib/widget/particle/particle_page.dart b/lib/widget/particle/particle_page.dart index 95956a8..0e982ab 100644 --- a/lib/widget/particle/particle_page.dart +++ b/lib/widget/particle/particle_page.dart @@ -6,21 +6,23 @@ import 'package:supercharged/supercharged.dart'; enum _ColorTween { color1, color2 } class ParticlePage extends StatelessWidget { + const ParticlePage({super.key}); + @override Widget build(BuildContext context) { - return new Scaffold( + return Scaffold( appBar: AppBar( - title: new Text("ParticlePage"), + title: const Text("ParticlePage"), ), backgroundColor: Colors.black, - body: Stack(children: [ + body: const Stack(children: [ Positioned.fill(child: AnimatedBackground()), Positioned.fill(child: ParticlesWidget(30)), Positioned.fill( - child: new Center( - child: new Text( + child: Center( + child: Text( "GSY Flutter Demo", - style: new TextStyle( + style: TextStyle( fontSize: 30, fontWeight: FontWeight.bold, color: Colors.white), @@ -33,17 +35,19 @@ class ParticlePage extends StatelessWidget { } class AnimatedBackground extends StatelessWidget { + const AnimatedBackground({super.key}); + @override Widget build(BuildContext context) { final tween = MovieTween() ..tween( _ColorTween.color1, - Color(0xffD38312).tweenTo(Colors.lightBlue.shade900), + const Color(0xffD38312).tweenTo(Colors.lightBlue.shade900), duration: 3.seconds, ) ..tween( _ColorTween.color2, - Color(0xffA83279).tweenTo(Colors.blue.shade600), + const Color(0xffA83279).tweenTo(Colors.blue.shade600), duration: 3.seconds, ); diff --git a/lib/widget/particle/particle_painter.dart b/lib/widget/particle/particle_painter.dart index b8f8791..6faa4f7 100644 --- a/lib/widget/particle/particle_painter.dart +++ b/lib/widget/particle/particle_painter.dart @@ -11,7 +11,7 @@ class ParticlePainter extends CustomPainter { void paint(Canvas canvas, Size size) { final paint = Paint()..color = Colors.white.withAlpha(50); - particles.forEach((particle) { + for (var particle in particles) { final progress = particle.progress(); final Movie animation = particle.tween.transform(progress); @@ -20,7 +20,7 @@ class ParticlePainter extends CustomPainter { animation.get(ParticleOffsetProps.y) * size.height, ); canvas.drawCircle(position, size.width * 0.2 * particle.size, paint); - }); + } } @override diff --git a/lib/widget/particle/particle_widget.dart b/lib/widget/particle/particle_widget.dart index 6704cb4..db85742 100644 --- a/lib/widget/particle/particle_widget.dart +++ b/lib/widget/particle/particle_widget.dart @@ -9,7 +9,7 @@ import 'package:supercharged/supercharged.dart'; class ParticlesWidget extends StatefulWidget { final int numberOfParticles; - ParticlesWidget(this.numberOfParticles); + const ParticlesWidget(this.numberOfParticles, {super.key}); @override _ParticlesWidgetState createState() => _ParticlesWidgetState(); @@ -29,7 +29,7 @@ class _ParticlesWidgetState extends State { @override Widget build(BuildContext context) { return LoopAnimationBuilder( - duration: Duration(seconds: 1), + duration: const Duration(seconds: 1), tween: ConstantTween(1), builder: (context, child, dynamic _) { _simulateParticles(); @@ -41,8 +41,9 @@ class _ParticlesWidgetState extends State { } _simulateParticles() { - particles - .forEach((particle) => particle.checkIfParticleNeedsToBeRestarted()); + for (var particle in particles) { + particle.checkIfParticleNeedsToBeRestarted(); + } } } diff --git a/lib/widget/photo_gallery_demo_page.dart b/lib/widget/photo_gallery_demo_page.dart index dd09cc9..1840118 100644 --- a/lib/widget/photo_gallery_demo_page.dart +++ b/lib/widget/photo_gallery_demo_page.dart @@ -1,5 +1,6 @@ import 'dart:math'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_animate/flutter_animate.dart'; @@ -7,7 +8,7 @@ import 'package:flutter_animate/flutter_animate.dart'; /// 来自 https://github.com/gskinnerTeam/flutter-wonderous-app 上的一个 UI 效果 /// 文章 https://juejin.cn/post/7212249660581249082 class PhotoGalleryDemoPage extends StatefulWidget { - const PhotoGalleryDemoPage({Key? key}) : super(key: key); + const PhotoGalleryDemoPage({super.key}); @override State createState() => _PhotoGalleryDemoPageState(); @@ -16,12 +17,12 @@ class PhotoGalleryDemoPage extends StatefulWidget { class _PhotoGalleryDemoPageState extends State { @override Widget build(BuildContext context) { - return PhotoGallery(); + return const PhotoGallery(); } } class PhotoGallery extends StatefulWidget { - const PhotoGallery({Key? key}) : super(key: key); + const PhotoGallery({super.key}); @override State createState() => _PhotoGalleryState(); @@ -93,12 +94,15 @@ class _PhotoGalleryState extends State { ///这里判断下 index 是不是超出位置 // After calculating new index, exit early if we don't like it... - if (newIndex < 0 || newIndex > _imgCount - 1) + if (newIndex < 0 || newIndex > _imgCount - 1) { return; // keep the index in range - if (dir.dx < 0 && newIndex % _gridSize == 0) + } + if (dir.dx < 0 && newIndex % _gridSize == 0) { return; // prevent right-swipe when at right side - if (dir.dx > 0 && newIndex % _gridSize == _gridSize - 1) + } + if (dir.dx > 0 && newIndex % _gridSize == _gridSize - 1) { return; // prevent left-swipe when at left side + } /// 响应 _lastSwipeDir = dir; HapticFeedback.lightImpact(); @@ -106,7 +110,9 @@ class _PhotoGalleryState extends State { } void _setIndex(int value, {bool skipAnimation = false}) { - print("######## $value"); + if (kDebugMode) { + print("######## $value"); + } if (value < 0 || value >= _imgCount) return; _skipNextOffsetTween = skipAnimation; setState(() => _index = value); @@ -166,10 +172,10 @@ class _PhotoGalleryState extends State { var padding = _getPadding(MediaQuery.sizeOf(context)); final cutoutTweenDuration = - _skipNextOffsetTween ? Duration.zero : Duration(milliseconds: 600) * .5; + _skipNextOffsetTween ? Duration.zero : const Duration(milliseconds: 600) * .5; final offsetTweenDuration = - _skipNextOffsetTween ? Duration.zero : Duration(milliseconds: 600) * .4; + _skipNextOffsetTween ? Duration.zero : const Duration(milliseconds: 600) * .4; var gridOffset = _calculateCurrentOffset(padding, imgSize); gridOffset += Offset(0, -MediaQuery.paddingOf(context).top / 2); @@ -200,7 +206,7 @@ class _PhotoGalleryState extends State { builder: (_, value, child) => Transform.translate(offset: value, child: child), child: GridView.count( - physics: NeverScrollableScrollPhysics(), + physics: const NeverScrollableScrollPhysics(), crossAxisCount: _gridSize, childAspectRatio: imgSize.aspectRatio, mainAxisSpacing: padding, @@ -217,11 +223,10 @@ class _PhotoGalleryState extends State { class EightWaySwipeDetector extends StatefulWidget { const EightWaySwipeDetector( - {Key? key, + {super.key, required this.child, this.threshold = 50, - required this.onSwipe}) - : super(key: key); + required this.onSwipe}); final Widget child; final double threshold; final void Function(Offset dir)? onSwipe; @@ -298,14 +303,12 @@ class _EightWaySwipeDetectorState extends State { class _AnimatedCutoutOverlay extends StatelessWidget { const _AnimatedCutoutOverlay( - {Key? key, - required this.child, + {required this.child, required this.cutoutSize, required this.animationKey, this.duration, required this.swipeDir, - required this.opacity}) - : super(key: key); + required this.opacity}); final Widget child; final Size cutoutSize; final Key animationKey; @@ -370,7 +373,7 @@ class _CutoutClipper extends CustomClipper { padY, size.width - padX, size.height - padY, - Radius.circular(6), + const Radius.circular(6), ), ) ..close(), @@ -383,11 +386,13 @@ class _CutoutClipper extends CustomClipper { } class ShowPathDifference extends StatelessWidget { + const ShowPathDifference({super.key}); + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text('ShowPathDifference'), + title: const Text('ShowPathDifference'), ), body: Stack( alignment: Alignment.center, @@ -396,7 +401,7 @@ class ShowPathDifference extends StatelessWidget { child: Container( width: 300, height: 300, - decoration: BoxDecoration( + decoration: const BoxDecoration( image: DecorationImage( fit: BoxFit.cover, image: AssetImage("static/gsy_cat.png"), @@ -425,9 +430,9 @@ class ShowPathDifferencePainter extends CustomPainter { PathOperation.difference, Path() ..addRRect( - RRect.fromLTRBR(-150, -150, 150, 150, Radius.circular(10))), + RRect.fromLTRBR(-150, -150, 150, 150, const Radius.circular(10))), Path() - ..addOval(Rect.fromCircle(center: Offset(0, 0), radius: 100)) + ..addOval(Rect.fromCircle(center: const Offset(0, 0), radius: 100)) ..close(), ), paint, diff --git a/lib/widget/png_shadow_demo_page.dart b/lib/widget/png_shadow_demo_page.dart index 30c1fac..b8eae76 100644 --- a/lib/widget/png_shadow_demo_page.dart +++ b/lib/widget/png_shadow_demo_page.dart @@ -4,7 +4,7 @@ import 'package:flutter/material.dart'; ///from https://pub.flutter-io.cn/packages/drop_shadow class PngShadowDemoPage extends StatefulWidget { - const PngShadowDemoPage({Key? key}) : super(key: key); + const PngShadowDemoPage({super.key}); @override State createState() => _PngShadowDemoPageState(); @@ -15,7 +15,7 @@ class _PngShadowDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("PngShadowDemoPage"), + title: const Text("PngShadowDemoPage"), ), body: Container( alignment: Alignment.center, @@ -39,14 +39,14 @@ class DropShadow extends StatelessWidget { final double spread; const DropShadow({ - Key? key, + super.key, required this.child, this.blurRadius = 10.0, this.borderRadius = 0.0, this.offset = const Offset(0.0, 8.0), this.opacity = 1.0, this.spread = 1.0, - }) : super(key: key); + }); @override Widget build(BuildContext context) { diff --git a/lib/widget/positioned_demo_page.dart b/lib/widget/positioned_demo_page.dart index 98e4d0f..1552fb6 100644 --- a/lib/widget/positioned_demo_page.dart +++ b/lib/widget/positioned_demo_page.dart @@ -2,45 +2,47 @@ import 'package:flutter/material.dart'; ///Stack + Positioned例子 class PositionedDemoPage extends StatelessWidget { + const PositionedDemoPage({super.key}); + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("PositionedDemoPage"), + title: const Text("PositionedDemoPage"), ), body: Container( width: MediaQuery.sizeOf(context).width, height: MediaQuery.sizeOf(context).height, - margin: EdgeInsets.all(15), - child: new Stack( + margin: const EdgeInsets.all(15), + child: Stack( children: [ - new MaterialButton( + MaterialButton( onPressed: () {}, color: Colors.blue, ), - new Positioned( - child: new MaterialButton( + Positioned( + left: MediaQuery.sizeOf(context).width / 2, + child: MaterialButton( onPressed: () {}, color: Colors.greenAccent, - ), - left: MediaQuery.sizeOf(context).width / 2), - new Positioned( - child: new MaterialButton( - onPressed: () {}, - color: Colors.yellow, - ), + )), + Positioned( left: MediaQuery.sizeOf(context).width / 5, top: MediaQuery.sizeOf(context).height / 4 * 3, - ), - new Positioned( - child: new MaterialButton( + child: MaterialButton( onPressed: () {}, - color: Colors.redAccent, + color: Colors.yellow, ), + ), + Positioned( left: MediaQuery.sizeOf(context).width / 2 - Theme.of(context).buttonTheme.minWidth / 2, top: MediaQuery.sizeOf(context).height / 2 - MediaQuery.paddingOf(context).top - kToolbarHeight, + child: MaterialButton( + onPressed: () {}, + color: Colors.redAccent, + ), ), ], ), diff --git a/lib/widget/refrsh_demo_page.dart b/lib/widget/refrsh_demo_page.dart index 7c4c5b6..1b0eb2b 100644 --- a/lib/widget/refrsh_demo_page.dart +++ b/lib/widget/refrsh_demo_page.dart @@ -4,6 +4,8 @@ import 'package:flutter/material.dart'; ///比较粗略,没有做互斥等 ///详细使用还请查看 https://github.com/CarGuo/GSYGithubAppFlutter class RefreshDemoPage extends StatefulWidget { + const RefreshDemoPage({super.key}); + @override _RefreshDemoPageState createState() => _RefreshDemoPageState(); } @@ -15,12 +17,12 @@ class _RefreshDemoPageState extends State { List dataList = []; - final ScrollController _scrollController = new ScrollController(); + final ScrollController _scrollController = ScrollController(); - final GlobalKey refreshKey = new GlobalKey(); + final GlobalKey refreshKey = GlobalKey(); Future onRefresh() async { - await Future.delayed(Duration(seconds: 2)); + await Future.delayed(const Duration(seconds: 2)); dataList.clear(); for (int i = 0; i < pageSize; i++) { dataList.add("refresh"); @@ -32,7 +34,7 @@ class _RefreshDemoPageState extends State { } Future loadMore() async { - await Future.delayed(Duration(seconds: 2)); + await Future.delayed(const Duration(seconds: 2)); for (int i = 0; i < pageSize; i++) { dataList.add("loadmore"); } @@ -52,7 +54,7 @@ class _RefreshDemoPageState extends State { loadMore(); } }); - Future.delayed(Duration(seconds: 0), (){ + Future.delayed(const Duration(seconds: 0), (){ refreshKey.currentState!.show(); }); } @@ -67,46 +69,44 @@ class _RefreshDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("RefreshDemoPage"), + title: const Text("RefreshDemoPage"), ), - body: Container( - child: new RefreshIndicator( - ///GlobalKey,用户外部获取RefreshIndicator的State,做显示刷新 - key: refreshKey, - - ///下拉刷新触发,返回的是一个Future - onRefresh: onRefresh, - child: new ListView.builder( - ///保持ListView任何情况都能滚动,解决在RefreshIndicator的兼容问题。 - physics: const AlwaysScrollableScrollPhysics(), - - ///根据状态返回 - itemBuilder: (context, index) { - if (index == dataList.length) { - return new Container( - margin: EdgeInsets.all(10), - child: Align( - child: CircularProgressIndicator(), - ), - ); - } - return Card( - child: new Container( - height: 60, - alignment: Alignment.centerLeft, - child: new Text("Item ${dataList[index]} $index"), + body: RefreshIndicator( + ///GlobalKey,用户外部获取RefreshIndicator的State,做显示刷新 + key: refreshKey, + + ///下拉刷新触发,返回的是一个Future + onRefresh: onRefresh, + child: ListView.builder( + ///保持ListView任何情况都能滚动,解决在RefreshIndicator的兼容问题。 + physics: const AlwaysScrollableScrollPhysics(), + + ///根据状态返回 + itemBuilder: (context, index) { + if (index == dataList.length) { + return Container( + margin: const EdgeInsets.all(10), + child: const Align( + child: CircularProgressIndicator(), ), ); - }, + } + return Card( + child: Container( + height: 60, + alignment: Alignment.centerLeft, + child: Text("Item ${dataList[index]} $index"), + ), + ); + }, - ///根据状态返回数量 - itemCount: (dataList.length >= pageSize) - ? dataList.length + 1 - : dataList.length, + ///根据状态返回数量 + itemCount: (dataList.length >= pageSize) + ? dataList.length + 1 + : dataList.length, - ///滑动监听 - controller: _scrollController, - ), + ///滑动监听 + controller: _scrollController, ), ), ); diff --git a/lib/widget/refrsh_demo_page2.dart b/lib/widget/refrsh_demo_page2.dart index 0090bcd..816984c 100644 --- a/lib/widget/refrsh_demo_page2.dart +++ b/lib/widget/refrsh_demo_page2.dart @@ -5,6 +5,8 @@ import 'package:flutter/material.dart'; ///比较粗略,没有做互斥等 ///详细使用还请查看 https://github.com/CarGuo/GSYGithubAppFlutter class RefreshDemoPage2 extends StatefulWidget { + const RefreshDemoPage2({super.key}); + @override _RefreshDemoPageState2 createState() => _RefreshDemoPageState2(); } @@ -16,10 +18,10 @@ class _RefreshDemoPageState2 extends State { List dataList = []; - final ScrollController _scrollController = new ScrollController(); + final ScrollController _scrollController = ScrollController(); Future onRefresh() async { - await Future.delayed(Duration(seconds: 2)); + await Future.delayed(const Duration(seconds: 2)); dataList.clear(); for (int i = 0; i < pageSize; i++) { dataList.add("refresh"); @@ -31,7 +33,7 @@ class _RefreshDemoPageState2 extends State { } Future loadMore() async { - await Future.delayed(Duration(seconds: 2)); + await Future.delayed(const Duration(seconds: 2)); for (int i = 0; i < pageSize; i++) { dataList.add("loadmore"); } @@ -46,9 +48,9 @@ class _RefreshDemoPageState2 extends State { super.didChangeDependencies(); ///直接触发下拉 - new Future.delayed(const Duration(milliseconds: 500), () { + Future.delayed(const Duration(milliseconds: 500), () { _scrollController.animateTo(-141, - duration: Duration(milliseconds: 600), curve: Curves.linear); + duration: const Duration(milliseconds: 600), curve: Curves.linear); return true; }); } @@ -63,65 +65,63 @@ class _RefreshDemoPageState2 extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("RefreshDemoPage"), + title: const Text("RefreshDemoPage"), ), - body: Container( - child: new NotificationListener( - onNotification: (ScrollNotification notification) { - ///判断当前滑动位置是不是到达底部,触发加载更多回调 - if (notification is ScrollEndNotification) { - if (_scrollController.position.pixels > 0 && - _scrollController.position.pixels == - _scrollController.position.maxScrollExtent) { - loadMore(); - } + body: NotificationListener( + onNotification: (ScrollNotification notification) { + ///判断当前滑动位置是不是到达底部,触发加载更多回调 + if (notification is ScrollEndNotification) { + if (_scrollController.position.pixels > 0 && + _scrollController.position.pixels == + _scrollController.position.maxScrollExtent) { + loadMore(); } - return false; - }, - child: CustomScrollView( - controller: _scrollController, + } + return false; + }, + child: CustomScrollView( + controller: _scrollController, - ///回弹效果 - physics: const BouncingScrollPhysics( - parent: AlwaysScrollableScrollPhysics()), - slivers: [ - ///控制显示刷新的 CupertinoSliverRefreshControl - CupertinoSliverRefreshControl( - refreshIndicatorExtent: 100, - refreshTriggerPullDistance: 140, - onRefresh: onRefresh, - ), + ///回弹效果 + physics: const BouncingScrollPhysics( + parent: AlwaysScrollableScrollPhysics()), + slivers: [ + ///控制显示刷新的 CupertinoSliverRefreshControl + CupertinoSliverRefreshControl( + refreshIndicatorExtent: 100, + refreshTriggerPullDistance: 140, + onRefresh: onRefresh, + ), - ///列表区域 - SliverSafeArea( - sliver: SliverList( - ///代理显示 - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - if (index == dataList.length) { - return new Container( - margin: EdgeInsets.all(10), - child: Align( - child: CircularProgressIndicator(), - ), - ); - } - return Card( - child: new Container( - height: 60, - alignment: Alignment.centerLeft, - child: new Text("Item ${dataList[index]} $index"), + ///列表区域 + SliverSafeArea( + sliver: SliverList( + ///代理显示 + delegate: SliverChildBuilderDelegate( + (BuildContext context, int index) { + if (index == dataList.length) { + return Container( + margin: const EdgeInsets.all(10), + child: const Align( + child: CircularProgressIndicator(), ), ); - }, - childCount: (dataList.length >= pageSize) - ? dataList.length + 1 - : dataList.length, - ), + } + return Card( + child: Container( + height: 60, + alignment: Alignment.centerLeft, + child: Text("Item ${dataList[index]} $index"), + ), + ); + }, + childCount: (dataList.length >= pageSize) + ? dataList.length + 1 + : dataList.length, ), ), - ], - ), + ), + ], ), ), ); diff --git a/lib/widget/rich/real_rich_text.dart b/lib/widget/rich/real_rich_text.dart index cd2edb4..12fae91 100644 --- a/lib/widget/rich/real_rich_text.dart +++ b/lib/widget/rich/real_rich_text.dart @@ -1,6 +1,5 @@ import 'dart:ui' as ui show Image; -import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; @@ -40,9 +39,8 @@ import 'package:flutter/rendering.dart'; class RealRichText extends Text { final List textSpanList; - RealRichText( - this.textSpanList, { - Key? key, + const RealRichText( + this.textSpanList, {super.key, TextStyle? style, TextAlign textAlign = TextAlign.start, TextDirection? textDirection, @@ -62,13 +60,13 @@ class RealRichText extends Text { locale: locale); List extractAllNestedChildren(TextSpan textSpan) { - if (textSpan.children == null || textSpan.children!.length == 0) { + if (textSpan.children == null || textSpan.children!.isEmpty) { return [textSpan]; } List childrenSpan = []; - textSpan.children!.forEach((child) { + for (var child in textSpan.children!) { childrenSpan.addAll(extractAllNestedChildren(child as TextSpan)); - }); + } return childrenSpan; } @@ -76,11 +74,13 @@ class RealRichText extends Text { Widget build(BuildContext context) { final DefaultTextStyle defaultTextStyle = DefaultTextStyle.of(context); TextStyle? effectiveTextStyle = style; - if (style == null || style!.inherit) + if (style == null || style!.inherit) { effectiveTextStyle = defaultTextStyle.style.merge(style); - if (MediaQuery.boldTextOf(context)) + } + if (MediaQuery.boldTextOf(context)) { effectiveTextStyle = - effectiveTextStyle!.merge(TextStyle(fontWeight: FontWeight.bold)); + effectiveTextStyle!.merge(const TextStyle(fontWeight: FontWeight.bold)); + } TextSpan textSpan = TextSpan( style: effectiveTextStyle, @@ -92,11 +92,11 @@ class RealRichText extends Text { ))); // pass the context to ImageSpan to create a ImageConfiguration - textSpan.children!.forEach((f) { + for (var f in textSpan.children!) { if (f is ImageSpan) { f.updateImageConfiguration(context); } - }); + } Widget result = _RichTextWrapper( textAlign: textAlign ?? defaultTextStyle.textAlign ?? TextAlign.start, @@ -137,7 +137,7 @@ class ImageSpan extends TextSpan { this.imageWidth = 14.0, this.imageHeight = 14.0, this.margin, - GestureRecognizer? recognizer, + super.recognizer, }) : imageResolver = ImageResolver(imageProvider), super( style: TextStyle( @@ -148,8 +148,7 @@ class ImageSpan extends TextSpan { fontSize: (imageHeight / 1.15) + (margin == null ? 0 : margin.vertical)), text: "\u200B", - children: [], - recognizer: recognizer); + children: []); void updateImageConfiguration(BuildContext context) { imageResolver.updateImageConfiguration(context, imageWidth, imageHeight); @@ -191,12 +190,12 @@ class ImageResolver { _imageStream = imageProvider.resolve(_imageConfiguration!); assert(_imageStream != null); - this._listener = listener; + _listener = listener; if (_imageStream!.key != oldImageStream?.key) { if (imageStreamListener != null) { oldImageStream?.removeListener(imageStreamListener!); } - imageStreamListener ??= new ImageStreamListener(_handleImageChanged); + imageStreamListener ??= ImageStreamListener(_handleImageChanged); _imageStream!.addListener(imageStreamListener!); } } @@ -207,8 +206,8 @@ class ImageResolver { } void addListening() { - if (this._listener != null) { - imageStreamListener ??= new ImageStreamListener(_handleImageChanged); + if (_listener != null) { + imageStreamListener ??= ImageStreamListener(_handleImageChanged); _imageStream?.addListener(imageStreamListener!); } } @@ -226,26 +225,15 @@ class ImageResolver { /// No more special purpose. class _RichTextWrapper extends RichText { _RichTextWrapper({ - Key? key, - required TextSpan text, - TextAlign textAlign = TextAlign.start, - TextDirection? textDirection, - bool softWrap = true, - TextOverflow overflow = TextOverflow.clip, - TextScaler textScaler = TextScaler.noScaling, - int? maxLines, - Locale? locale, - }) : assert(maxLines == null || maxLines > 0), - super( - key: key, - text: text, - textAlign: textAlign, - textDirection: textDirection, - softWrap: softWrap, - overflow: overflow, - textScaler: textScaler, - maxLines: maxLines, - locale: locale); + required TextSpan super.text, + super.textAlign, + super.textDirection, + super.softWrap, + super.overflow, + super.textScaler, + super.maxLines, + super.locale, + }) : assert(maxLines == null || maxLines > 0); @override RenderParagraph createRenderObject(BuildContext context) { @@ -265,24 +253,14 @@ class _RichTextWrapper extends RichText { /// paint the image on the top of those ImageSpan's blank space class _RealRichRenderParagraph extends RenderParagraph { - _RealRichRenderParagraph(TextSpan text, - {required TextAlign textAlign, - required TextDirection textDirection, - required bool softWrap, - required TextOverflow overflow, - required TextScaler textScaler, - int? maxLines, - Locale? locale}) - : super( - text, - textAlign: textAlign, - textDirection: textDirection, - softWrap: softWrap, - overflow: overflow, - textScaler: textScaler, - maxLines: maxLines, - locale: locale, - ); + _RealRichRenderParagraph(TextSpan super.text, + {required super.textAlign, + required super.textDirection, + required super.softWrap, + required super.overflow, + required super.textScaler, + super.maxLines, + super.locale}); @override void paint(PaintingContext context, Offset offset) { @@ -295,21 +273,21 @@ class _RealRichRenderParagraph extends RenderParagraph { @override void attach(covariant Object owner) { super.attach(owner as PipelineOwner); - (text as TextSpan).children!.forEach((textSpan) { + for (var textSpan in (text as TextSpan).children!) { if (textSpan is ImageSpan) { textSpan.imageResolver.addListening(); } - }); + } } @override void detach() { super.detach(); - (text as TextSpan).children!.forEach((textSpan) { + for (var textSpan in (text as TextSpan).children!) { if (textSpan is ImageSpan) { textSpan.imageResolver.stopListening(); } - }); + } } @override diff --git a/lib/widget/rich_text_demo_page.dart b/lib/widget/rich_text_demo_page.dart index d647443..20fb27a 100644 --- a/lib/widget/rich_text_demo_page.dart +++ b/lib/widget/rich_text_demo_page.dart @@ -3,6 +3,8 @@ import 'package:flutter/material.dart'; import 'package:gsy_flutter_demo/widget/rich/real_rich_text.dart'; class RichTextDemoPage extends StatefulWidget { + const RichTextDemoPage({super.key}); + @override _RichTextDemoState createState() => _RichTextDemoState(); } @@ -12,37 +14,37 @@ class _RichTextDemoState extends State { Widget build(BuildContext mainContext) { return Scaffold( appBar: AppBar( - title: new Text("RichTextDemoPage"), + title: const Text("RichTextDemoPage"), ), - body: new Container( - margin: EdgeInsets.all(10), + body: Container( + margin: const EdgeInsets.all(10), child: Builder(builder: (context) { return Center( child: RealRichText([ TextSpan( text: "A Text Link", - style: TextStyle(color: Colors.red, fontSize: 14), + style: const TextStyle(color: Colors.red, fontSize: 14), recognizer: TapGestureRecognizer() ..onTap = () { show(context, "Link Clicked."); }, ), ImageSpan( - AssetImage("static/gsy_cat.png"), + const AssetImage("static/gsy_cat.png"), imageWidth: 24, imageHeight: 24, ), - ImageSpan(AssetImage("static/gsy_cat.png"), + ImageSpan(const AssetImage("static/gsy_cat.png"), imageWidth: 24, imageHeight: 24, - margin: EdgeInsets.symmetric(horizontal: 10)), - TextSpan( + margin: const EdgeInsets.symmetric(horizontal: 10)), + const TextSpan( text: "哈哈哈", style: TextStyle(color: Colors.yellow, fontSize: 14), ), TextSpan( text: "@Somebody", - style: TextStyle( + style: const TextStyle( color: Colors.black, fontSize: 14, fontWeight: FontWeight.bold), @@ -53,21 +55,21 @@ class _RichTextDemoState extends State { ), TextSpan( text: " #RealRichText# ", - style: TextStyle(color: Colors.blue, fontSize: 14), + style: const TextStyle(color: Colors.blue, fontSize: 14), recognizer: TapGestureRecognizer() ..onTap = () { show(context, "Link Clicked."); }, ), - TextSpan( + const TextSpan( text: "showing a bigger image", style: TextStyle(color: Colors.black, fontSize: 14), ), - ImageSpan(AssetImage("static/gsy_cat.png"), + ImageSpan(const AssetImage("static/gsy_cat.png"), imageWidth: 24, imageHeight: 24, - margin: EdgeInsets.symmetric(horizontal: 5)), - TextSpan( + margin: const EdgeInsets.symmetric(horizontal: 5)), + const TextSpan( text: "and seems working perfect……", style: TextStyle(color: Colors.black, fontSize: 14), ), @@ -84,7 +86,7 @@ class _RichTextDemoState extends State { action: SnackBarAction( label: 'ACTION', onPressed: () { - ScaffoldMessenger.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( content: Text('You pressed snackbar\'s action.'), )); }, diff --git a/lib/widget/rich_text_demo_page2.dart b/lib/widget/rich_text_demo_page2.dart index 7d70b03..eab231c 100644 --- a/lib/widget/rich_text_demo_page2.dart +++ b/lib/widget/rich_text_demo_page2.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; class RichTextDemoPage2 extends StatefulWidget { + const RichTextDemoPage2({super.key}); + @override _RichTextDemoState2 createState() => _RichTextDemoState2(); } @@ -12,7 +14,7 @@ class _RichTextDemoState2 extends State { Widget build(BuildContext mainContext) { return Scaffold( appBar: AppBar( - title: new Text("RichTextDemoPage"), + title: const Text("RichTextDemoPage"), actions: [ IconButton( onPressed: () { @@ -20,7 +22,7 @@ class _RichTextDemoState2 extends State { size += 10; }); }, - icon: Icon(Icons.add_circle_outline), + icon: const Icon(Icons.add_circle_outline), ), IconButton( onPressed: () { @@ -28,19 +30,19 @@ class _RichTextDemoState2 extends State { size -= 10; }); }, - icon: Icon(Icons.remove_circle_outline), + icon: const Icon(Icons.remove_circle_outline), ) ], ), body: SelectionArea( - child: new Container( - margin: EdgeInsets.all(10), + child: Container( + margin: const EdgeInsets.all(10), child: Builder(builder: (context) { return Center( child: Text.rich(TextSpan( children: [ - TextSpan(text: 'Flutter is'), - WidgetSpan( + const TextSpan(text: 'Flutter is'), + const WidgetSpan( child: SizedBox( width: 120, height: 50, @@ -52,13 +54,13 @@ class _RichTextDemoState2 extends State { child: SizedBox( width: size > 0 ? size : 0, height: size > 0 ? size : 0, - child: new Image.asset( + child: Image.asset( "static/gsy_cat.png", fit: BoxFit.cover, ), )), - TextSpan(text: 'the best!'), - WidgetSpan( + const TextSpan(text: 'the best!'), + const WidgetSpan( child: SelectionContainer.disabled( child: Text(' not copy'), ), @@ -78,7 +80,7 @@ class _RichTextDemoState2 extends State { action: SnackBarAction( label: 'ACTION', onPressed: () { - ScaffoldMessenger.of(context).showSnackBar(SnackBar( + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( content: Text('You pressed snackbar\'s action.'), )); }, diff --git a/lib/widget/route_demo_page.dart b/lib/widget/route_demo_page.dart index de0d303..d36df67 100644 --- a/lib/widget/route_demo_page.dart +++ b/lib/widget/route_demo_page.dart @@ -2,7 +2,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class RouteDemoPage extends StatefulWidget { - const RouteDemoPage({Key? key}) : super(key: key); + const RouteDemoPage({super.key}); @override State createState() => _RouteDemoPageState(); @@ -12,7 +12,7 @@ class _RouteDemoPageState extends State { final GlobalKey _navigator = GlobalKey(); getRouter(index) { - return new CupertinoPageRoute( + return CupertinoPageRoute( builder: (context) { return RoutePage(index); }, @@ -24,56 +24,54 @@ class _RouteDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("RouteDemoPage"), + title: const Text("RouteDemoPage"), ), - body: Container( - child: Row( - children: [ - Expanded( - child: Container( - color: Colors.blue, - child: new Column( - children: List.generate(10, (index) { - return InkWell( - onTap: () { - _navigator.currentState!.push(getRouter(index)); - }, - child: Container( - height: 30, - margin: EdgeInsets.symmetric(vertical: 10), - color: Colors.amberAccent, - alignment: Alignment.center, - child: Text("click $index"))); - }), - ), + body: Row( + children: [ + Expanded( + flex: 1, + child: Container( + color: Colors.blue, + child: Column( + children: List.generate(10, (index) { + return InkWell( + onTap: () { + _navigator.currentState!.push(getRouter(index)); + }, + child: Container( + height: 30, + margin: const EdgeInsets.symmetric(vertical: 10), + color: Colors.amberAccent, + alignment: Alignment.center, + child: Text("click $index"))); + }), ), - flex: 1, ), - new Divider( + ), + const Divider( + color: Colors.grey, + ), + const SizedBox( + width: 30, + ), + Expanded( + flex: 3, + child: Container( color: Colors.grey, - ), - new SizedBox( - width: 30, - ), - Expanded( - child: Container( - color: Colors.grey, - child: Navigator( - restorationScopeId: 'nav2', - key: _navigator, - onGenerateInitialRoutes: - (NavigatorState navigator, String initialRoute) { - return [ - getRouter(0), - ]; - }, - reportsRouteUpdateToEngine: true, - ), + child: Navigator( + restorationScopeId: 'nav2', + key: _navigator, + onGenerateInitialRoutes: + (NavigatorState navigator, String initialRoute) { + return [ + getRouter(0), + ]; + }, + reportsRouteUpdateToEngine: true, ), - flex: 3, ), - ], - ), + ), + ], ), ); } @@ -82,7 +80,7 @@ class _RouteDemoPageState extends State { class RoutePage extends StatefulWidget { final int index; - const RoutePage(this.index); + const RoutePage(this.index, {super.key}); @override State createState() => _RoutePageState(); @@ -103,9 +101,9 @@ class _RoutePageState extends State { height: 200, alignment: Alignment.center, color: Colors.amber, - child: new Text( + child: Text( "${widget.index}", - style: TextStyle(fontSize: 100, color: Colors.red), + style: const TextStyle(fontSize: 100, color: Colors.red), ), ), ), diff --git a/lib/widget/scroll_inner_content_demo_page.dart b/lib/widget/scroll_inner_content_demo_page.dart index ad7d17a..76730df 100644 --- a/lib/widget/scroll_inner_content_demo_page.dart +++ b/lib/widget/scroll_inner_content_demo_page.dart @@ -1,7 +1,10 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; ///一个有趣的底部跟随例子 class ScrollInnerContentDemoPage extends StatefulWidget { + const ScrollInnerContentDemoPage({super.key}); + @override _ScrollInnerContentDemoPageState createState() => _ScrollInnerContentDemoPageState(); @@ -9,14 +12,14 @@ class ScrollInnerContentDemoPage extends StatefulWidget { class _ScrollInnerContentDemoPageState extends State { - GlobalKey globalKey = new GlobalKey(); + GlobalKey globalKey = GlobalKey(); final double buttonHeight = 40; bool outSize = false; String content = "这是可滑动文本区域"; Future getButtonPosition() { - return Future.delayed(Duration(seconds: 0), () { + return Future.delayed(const Duration(seconds: 0), () { var renderBox = globalKey.currentContext!.findRenderObject() as RenderBox; double dy = renderBox.localToGlobal(Offset.zero).dy; double height = renderBox.size.height; @@ -37,7 +40,9 @@ class _ScrollInnerContentDemoPageState this.outSize = outSize; }); } - print("##### $buttonPosition $outSize"); + if (kDebugMode) { + print("##### $buttonPosition $outSize"); + } return buttonPosition; }); @@ -47,7 +52,7 @@ class _ScrollInnerContentDemoPageState Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("ScrollDemoPage"), + title: const Text("ScrollDemoPage"), actions: [ IconButton( onPressed: () { @@ -55,7 +60,7 @@ class _ScrollInnerContentDemoPageState content += "=|-动态文本-|="; }); }, - icon: Icon(Icons.add_circle_outline), + icon: const Icon(Icons.add_circle_outline), ), IconButton( onPressed: () { @@ -65,55 +70,51 @@ class _ScrollInnerContentDemoPageState } }); }, - icon: Icon(Icons.remove_circle_outline), + icon: const Icon(Icons.remove_circle_outline), ) ], ), - body: new Stack( + body: Stack( children: [ - new Container( - child: Column( - children: [ - new Container( - color: Colors.redAccent, - child: Column( - children: [ - new Container( - height: 60, - alignment: Alignment.centerLeft, - child: new Text( - "点击右上角加减查看效果", - style: TextStyle(fontSize: 18), - ), + Column( + children: [ + Container( + color: Colors.redAccent, + child: Column( + children: [ + Container( + height: 60, + alignment: Alignment.centerLeft, + child: const Text( + "点击右上角加减查看效果", + style: TextStyle(fontSize: 18), ), - new Container( - height: 60, - alignment: Alignment.centerLeft, - child: new Text("我是文本2"), - ), - ], - ), + ), + Container( + height: 60, + alignment: Alignment.centerLeft, + child: const Text("我是文本2"), + ), + ], ), - new Expanded( + ), + Expanded( + child: SingleChildScrollView( + padding: + EdgeInsets.only(bottom: outSize ? (buttonHeight) : 0), + physics: const ClampingScrollPhysics(), child: Container( - child: SingleChildScrollView( - padding: - EdgeInsets.only(bottom: outSize ? (buttonHeight) : 0), - physics: ClampingScrollPhysics(), - child: new Container( - width: MediaQuery.sizeOf(context).width, - key: globalKey, - color: Colors.red, - child: new Text( - content, - style: TextStyle(fontSize: 44), - ), - ), + width: MediaQuery.sizeOf(context).width, + key: globalKey, + color: Colors.red, + child: Text( + content, + style: const TextStyle(fontSize: 44), ), ), ), - ], - ), + ), + ], ), FutureBuilder( future: getButtonPosition(), @@ -121,21 +122,21 @@ class _ScrollInnerContentDemoPageState if (snap.data == null || snap.data == 0) { return Container(); } - return new Positioned( + return Positioned( top: snap.data, - child: new Container( + child: SizedBox( width: MediaQuery.sizeOf(context).width, height: buttonHeight, - child: new InkWell( + child: InkWell( onTap: () {}, - child: new Container( + child: Container( height: buttonHeight, alignment: Alignment.center, - margin: EdgeInsets.symmetric( + margin: const EdgeInsets.symmetric( horizontal: 20, ), color: Colors.blue, - child: new Text("#########"), + child: const Text("#########"), ), ), ), diff --git a/lib/widget/scroll_listener_demo_page.dart b/lib/widget/scroll_listener_demo_page.dart index 9cf374c..37dcfc2 100644 --- a/lib/widget/scroll_listener_demo_page.dart +++ b/lib/widget/scroll_listener_demo_page.dart @@ -2,12 +2,14 @@ import 'package:flutter/material.dart'; ///滑动监听 class ScrollListenerDemoPage extends StatefulWidget { + const ScrollListenerDemoPage({super.key}); + @override _ScrollListenerDemoPageState createState() => _ScrollListenerDemoPageState(); } class _ScrollListenerDemoPageState extends State { - final ScrollController _scrollController = new ScrollController(); + final ScrollController _scrollController = ScrollController(); bool isEnd = false; @@ -31,59 +33,57 @@ class _ScrollListenerDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("ScrollListenerDemoPage"), + title: const Text("ScrollListenerDemoPage"), ), - body: new Container( - child: NotificationListener( - onNotification: (dynamic notification) { - String notify = ""; - if (notification is ScrollEndNotification) { - notify = "ScrollEnd"; - } else if (notification is ScrollStartNotification) { - notify = "ScrollStart"; - } else if (notification is UserScrollNotification) { - notify = " UserScroll"; - } else if (notification is ScrollUpdateNotification) { - notify = "ScrollUpdate"; - } - setState(() { - this.notify = notify; - }); - return false; + body: NotificationListener( + onNotification: (dynamic notification) { + String notify = ""; + if (notification is ScrollEndNotification) { + notify = "ScrollEnd"; + } else if (notification is ScrollStartNotification) { + notify = "ScrollStart"; + } else if (notification is UserScrollNotification) { + notify = " UserScroll"; + } else if (notification is ScrollUpdateNotification) { + notify = "ScrollUpdate"; + } + setState(() { + this.notify = notify; + }); + return false; + }, + child: ListView.builder( + controller: _scrollController, + itemBuilder: (context, index) { + return Card( + child: Container( + height: 60, + alignment: Alignment.centerLeft, + child: Text("Item $index"), + ), + ); }, - child: new ListView.builder( - controller: _scrollController, - itemBuilder: (context, index) { - return Card( - child: new Container( - height: 60, - alignment: Alignment.centerLeft, - child: new Text("Item $index"), - ), - ); - }, - itemCount: 100, - ), + itemCount: 100, ), ), persistentFooterButtons: [ - new TextButton( + TextButton( onPressed: () { _scrollController.animateTo(0, - duration: Duration(seconds: 1), curve: Curves.bounceInOut); + duration: const Duration(seconds: 1), curve: Curves.bounceInOut); }, - child: new Text("position: ${offset.floor()}"), + child: Text("position: ${offset.floor()}"), ), - new Container(width: 0.3, height: 30.0), - new TextButton( + const SizedBox(width: 0.3, height: 30.0), + TextButton( onPressed: () {}, - child: new Text(notify), + child: Text(notify), ), - new Visibility( + Visibility( visible: isEnd, - child: new TextButton( + child: TextButton( onPressed: () {}, - child: new Text("到达底部"), + child: const Text("到达底部"), ), ) ], diff --git a/lib/widget/scroll_to_index_demo_page.dart b/lib/widget/scroll_to_index_demo_page.dart index 1152978..67a7a13 100644 --- a/lib/widget/scroll_to_index_demo_page.dart +++ b/lib/widget/scroll_to_index_demo_page.dart @@ -7,6 +7,8 @@ import 'package:scroll_to_index/scroll_to_index.dart'; /// 因为官方一直未支持滑动都执行 item /// 所有有第三方库另辟蹊径 class ScrollToIndexDemoPage extends StatefulWidget { + const ScrollToIndexDemoPage({super.key}); + @override _ScrollToIndexDemoPageState createState() => _ScrollToIndexDemoPageState(); } @@ -40,7 +42,7 @@ class _ScrollToIndexDemoPageState extends State { return _wrapScrollTag( index: index, child: Container( - padding: EdgeInsets.all(8), + padding: const EdgeInsets.all(8), alignment: Alignment.topCenter, height: height, decoration: BoxDecoration( @@ -54,37 +56,35 @@ class _ScrollToIndexDemoPageState extends State { key: ValueKey(index), controller: controller!, index: index, - child: child, highlightColor: Colors.black.withOpacity(0.1), + child: child, ); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("ScrollToIndexDemoPage"), + title: const Text("ScrollToIndexDemoPage"), ), - body: new Container( - child: ListView( - scrollDirection: scrollDirection, - controller: controller, - children: randomList.map((data) { - return Padding( - padding: EdgeInsets.all(8), - child: _getRow(data[0], math.max(data[1].toDouble(), 50.0)), - ); - }).toList(), - ), + body: ListView( + scrollDirection: scrollDirection, + controller: controller, + children: randomList.map((data) { + return Padding( + padding: const EdgeInsets.all(8), + child: _getRow(data[0], math.max(data[1].toDouble(), 50.0)), + ); + }).toList(), ), persistentFooterButtons: [ - new TextButton( + TextButton( onPressed: () async { ///滑动到第13个的位置 await controller!.scrollToIndex(13, preferPosition: AutoScrollPosition.begin); controller!.highlight(13); }, - child: new Text("Scroll to 13"), + child: const Text("Scroll to 13"), ), ], ); diff --git a/lib/widget/scroll_to_index_demo_page2.dart b/lib/widget/scroll_to_index_demo_page2.dart index 0f37f09..a2a4fce 100644 --- a/lib/widget/scroll_to_index_demo_page2.dart +++ b/lib/widget/scroll_to_index_demo_page2.dart @@ -1,10 +1,13 @@ import 'dart:math' as math; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; /// 滑动到指定位置 GlobalKey 版本 /// 基于 SingleChildScrollView 和 Column class ScrollToIndexDemoPage2 extends StatefulWidget { + const ScrollToIndexDemoPage2({super.key}); + @override _ScrollToIndexDemoPageState2 createState() => _ScrollToIndexDemoPageState2(); } @@ -12,7 +15,7 @@ class ScrollToIndexDemoPage2 extends StatefulWidget { class _ScrollToIndexDemoPageState2 extends State { GlobalKey scrollKey = GlobalKey(); - ScrollController controller = new ScrollController(); + ScrollController controller = ScrollController(); List dataList = []; @@ -20,7 +23,7 @@ class _ScrollToIndexDemoPageState2 extends State { void initState() { dataList.clear(); for (int i = 0; i < 100; i++) { - dataList.add(new ItemModel(i)); + dataList.add(ItemModel(i)); } super.initState(); } @@ -30,46 +33,46 @@ class _ScrollToIndexDemoPageState2 extends State { ///获取 renderBox RenderBox renderBox = - key.globalKey.currentContext!.findRenderObject() as RenderBox; + key.globalKey.currentContext!.findRenderObject() as RenderBox; ///获取位置偏移,基于 ancestor: SingleChildScrollView 的 RenderObject() double dy = renderBox .localToGlobal(Offset.zero, - ancestor: scrollKey.currentContext!.findRenderObject()) + ancestor: scrollKey.currentContext!.findRenderObject()) .dy; ///计算真实位移 var offset = dy + controller.offset; - print("*******$offset"); + if (kDebugMode) { + print("*******$offset"); + } controller.animateTo(offset, - duration: Duration(milliseconds: 500), curve: Curves.linear); + duration: const Duration(milliseconds: 500), curve: Curves.linear); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("ScrollToIndexDemoPage2"), + title: const Text("ScrollToIndexDemoPage2"), ), - body: new Container( - child: SingleChildScrollView( - key: scrollKey, - controller: controller, - child: Column( - children: dataList.map((data) { - return CardItem(data, key: dataList[data.index].globalKey); - }).toList(), - ), + body: SingleChildScrollView( + key: scrollKey, + controller: controller, + child: Column( + children: dataList.map((data) { + return CardItem(data, key: dataList[data.index].globalKey); + }).toList(), ), ), persistentFooterButtons: [ - new TextButton( + TextButton( onPressed: () async { _scrollToIndex(); }, - child: new Text("Scroll to 12"), + child: const Text("Scroll to 12"), ), ], ); @@ -77,24 +80,21 @@ class _ScrollToIndexDemoPageState2 extends State { } class CardItem extends StatelessWidget { - - final random = math.Random(); - final ItemModel data; - CardItem(this.data, {key}) : super(key: key); + CardItem(this.data, {super.key}); @override Widget build(BuildContext context) { return Card( - child: new Container( + child: Container( height: (300 * random.nextDouble()), alignment: Alignment.centerLeft, - child: new Container( - margin: EdgeInsets.all(5), - child: new Text("Item ${data.index}"), + child: Container( + margin: const EdgeInsets.all(5), + child: Text("Item ${data.index}"), ), ), ); @@ -103,7 +103,7 @@ class CardItem extends StatelessWidget { class ItemModel { ///这个key是关键 - GlobalKey globalKey = new GlobalKey(); + GlobalKey globalKey = GlobalKey(); ///可以添加你的代码 final int index; diff --git a/lib/widget/shader_canvas_demo_page.dart b/lib/widget/shader_canvas_demo_page.dart index 6410081..7eb0212 100644 --- a/lib/widget/shader_canvas_demo_page.dart +++ b/lib/widget/shader_canvas_demo_page.dart @@ -4,18 +4,20 @@ import 'dart:ui' as ui; import 'package:flutter/material.dart'; class ShaderCanvasDemoPage extends StatelessWidget { + const ShaderCanvasDemoPage({super.key}); + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("ShaderCanvasDemoPage"), + title: const Text("ShaderCanvasDemoPage"), ), extendBody: true, - body: Column( + body: const Column( children: [ ///增加 CustomWidget CanvasWidgetA(), - new SizedBox( + SizedBox( height: 5, ), CanvasWidgetB(), @@ -26,10 +28,12 @@ class ShaderCanvasDemoPage extends StatelessWidget { } class CanvasWidgetA extends StatelessWidget { + const CanvasWidgetA({super.key}); + @override Widget build(BuildContext context) { return LayoutBuilder(builder: (context, constraints) { - return Container( + return SizedBox( height: 100, width: constraints.biggest.width, child: CustomPaint( @@ -51,10 +55,10 @@ class CurvePainterA extends CustomPainter { final paint = Paint()..color = Colors.blue.withAlpha(60); - var radientColors = [Color(0x01333333), Color(0x44333333)]; //渐变颜色数组 + var radientColors = [const Color(0x01333333), const Color(0x44333333)]; //渐变颜色数组 ui.Gradient gradient = ui.Gradient.linear( - Offset(0, 0), Offset(size.width, size.height), radientColors); + const Offset(0, 0), Offset(size.width, size.height), radientColors); shader.shader = gradient; final path = Path(); @@ -85,10 +89,12 @@ class CurvePainterA extends CustomPainter { } class CanvasWidgetB extends StatelessWidget { + const CanvasWidgetB({super.key}); + @override Widget build(BuildContext context) { return LayoutBuilder(builder: (context, constraints) { - return Container( + return SizedBox( height: 100, width: constraints.biggest.width, child: CustomPaint( diff --git a/lib/widget/silder_verify_page.dart b/lib/widget/silder_verify_page.dart index 8e24371..7ce04d8 100644 --- a/lib/widget/silder_verify_page.dart +++ b/lib/widget/silder_verify_page.dart @@ -1,21 +1,19 @@ import 'package:flutter/material.dart'; class SlideVerifyPage extends StatelessWidget { - const SlideVerifyPage({Key? key}) : super(key: key); + const SlideVerifyPage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("SlideVerifyPage"), + title: const Text("SlideVerifyPage"), ), - body: Container( - child: Center( - child: SlideVerify( - sliderImage: "static/gsy_cat.png", - successText: "验证成功", - initText: "滑动验证", - ), + body: const Center( + child: SlideVerify( + sliderImage: "static/gsy_cat.png", + successText: "验证成功", + initText: "滑动验证", ), ), ); @@ -37,7 +35,7 @@ class SlideVerify extends StatefulWidget { final VoidCallback? successListener; const SlideVerify( - {Key? key, + {super.key, this.height = 60, this.width = 250, this.successText, @@ -50,8 +48,7 @@ class SlideVerify extends StatefulWidget { this.bgColor = Colors.grey, this.moveColor = Colors.blue, this.borderColor = Colors.blueAccent, - this.successListener}) - : super(key: key); + this.successListener}); @override State createState() { @@ -98,8 +95,8 @@ class SlideVerifyState extends State @override void initState() { super.initState(); - this.width = widget.width; - this.height = widget.height; + width = widget.width; + height = widget.height; _init(); } @@ -150,7 +147,7 @@ class SlideVerifyState extends State decoration: BoxDecoration( color: widget.bgColor, border: Border.all(color: widget.borderColor), - borderRadius: BorderRadius.all(new Radius.circular(height))), + borderRadius: BorderRadius.all(Radius.circular(height))), child: Stack( alignment: Alignment.centerLeft, children: [ @@ -187,7 +184,7 @@ class SlideVerifyState extends State decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all( - new Radius.circular(sliderWidth), + Radius.circular(sliderWidth), ), ), child: Row( diff --git a/lib/widget/sliver_list_demo_page.dart b/lib/widget/sliver_list_demo_page.dart index ffff126..32215af 100644 --- a/lib/widget/sliver_list_demo_page.dart +++ b/lib/widget/sliver_list_demo_page.dart @@ -5,6 +5,8 @@ import 'package:flutter/material.dart' as W; import 'package:flutter/rendering.dart'; class SliverListDemoPage extends StatefulWidget { + const SliverListDemoPage({super.key}); + @override _SliverListDemoPageState createState() => _SliverListDemoPageState(); } @@ -25,7 +27,7 @@ class _SliverListDemoPageState extends State curve: Curves.bounceInOut, duration: const Duration(milliseconds: 10), ), - child: new Container( + child: Container( color: Colors.redAccent, ), ), @@ -53,34 +55,34 @@ class _SliverListDemoPageState extends State child: Padding( padding: EdgeInsets.only( bottom: 10, left: lr, right: lr, top: lr), - child: new Row( + child: Row( mainAxisSize: MainAxisSize.max, children: [ - new Expanded( - child: new Container( + Expanded( + child: Container( alignment: Alignment.center, color: Colors.orangeAccent, - child: new TextButton( + child: TextButton( onPressed: () { setState(() { listCount = 30; }); }, - child: new Text("按键1"), + child: const Text("按键1"), ), ), ), - new Expanded( - child: new Container( + Expanded( + child: Container( alignment: Alignment.center, color: Colors.orangeAccent, - child: new TextButton( + child: TextButton( onPressed: () { setState(() { listCount = 4; }); }, - child: new Text("按键2"), + child: const Text("按键2"), ), ), ), @@ -98,38 +100,36 @@ class _SliverListDemoPageState extends State Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("SliverListDemoPage"), + title: const Text("SliverListDemoPage"), ), - body: new Container( - child: NestedScrollView( - physics: const AlwaysScrollableScrollPhysics(), - headerSliverBuilder: _sliverBuilder, - body: CustomScrollView( - slivers: [ - W.Builder( - builder: (context) { - return SliverOverlapInjector( - handle: NestedScrollView.sliverOverlapAbsorberHandleFor( - context)); + body: NestedScrollView( + physics: const AlwaysScrollableScrollPhysics(), + headerSliverBuilder: _sliverBuilder, + body: CustomScrollView( + slivers: [ + W.Builder( + builder: (context) { + return SliverOverlapInjector( + handle: NestedScrollView.sliverOverlapAbsorberHandleFor( + context)); + }, + ), + SliverList( + delegate: SliverChildBuilderDelegate( + (context, index) { + return Card( + child: Container( + height: 60, + padding: const EdgeInsets.only(left: 10), + alignment: Alignment.centerLeft, + child: Text("Item $index"), + ), + ); }, + childCount: 100, ), - SliverList( - delegate: SliverChildBuilderDelegate( - (context, index) { - return Card( - child: new Container( - height: 60, - padding: EdgeInsets.only(left: 10), - alignment: Alignment.centerLeft, - child: new Text("Item $index"), - ), - ); - }, - childCount: 100, - ), - ) - ], - ), + ) + ], ), ), ); @@ -183,5 +183,5 @@ class GSYSliverHeaderDelegate extends SliverPersistentHeaderDelegate { FloatingHeaderSnapConfiguration get snapConfiguration => snapConfig; } -typedef Widget Builder( +typedef Builder = Widget Function( BuildContext context, double shrinkOffset, bool overlapsContent); diff --git a/lib/widget/sliver_stick_demo_page.dart b/lib/widget/sliver_stick_demo_page.dart index e6b3c42..cc583d2 100644 --- a/lib/widget/sliver_stick_demo_page.dart +++ b/lib/widget/sliver_stick_demo_page.dart @@ -6,13 +6,15 @@ import 'package:flutter/rendering.dart'; ///用 Sliver 的模式实现 Stick ///目前的实现方式就是性能不大好 class SliverStickListDemoPage extends StatefulWidget { + const SliverStickListDemoPage({super.key}); + @override _SliverStickListDemoPageState createState() => _SliverStickListDemoPageState(); } class _SliverStickListDemoPageState extends State { - ScrollController scrollController = new ScrollController(); + ScrollController scrollController = ScrollController(); List slivers = []; @@ -28,30 +30,30 @@ class _SliverStickListDemoPageState extends State { slivers.add( SliverHeaderItem( i, - child: new Container( + headerHeight: headerHeight, + contentHeight: contentHeight, + child: Container( height: headerHeight, alignment: Alignment.center, color: Colors.redAccent, - child: new Container( - padding: EdgeInsets.symmetric(horizontal: 10), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10), alignment: Alignment.centerLeft, height: headerHeight, - child: new Text("Header $i"), + child: Text("Header $i"), ), ), - headerHeight: headerHeight, - contentHeight: contentHeight, ), ); ///内容 slivers.add( SliverToBoxAdapter( - child: new Container( + child: Container( height: contentHeight, - padding: EdgeInsets.only(left: 10), + padding: const EdgeInsets.only(left: 10), alignment: Alignment.centerLeft, - child: new Text("Content $i"), + child: Text("Content $i"), ), ), ); @@ -61,7 +63,7 @@ class _SliverStickListDemoPageState extends State { @override void didChangeDependencies() { super.didChangeDependencies(); - Future.delayed(Duration(seconds: 0), () { + Future.delayed(const Duration(seconds: 0), () { setState(() { initItem(); }); @@ -72,14 +74,12 @@ class _SliverStickListDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("SliverListDemoPage"), + title: const Text("SliverListDemoPage"), ), - body: new Container( - child: CustomScrollView( - controller: scrollController, - physics: const AlwaysScrollableScrollPhysics(), - slivers: slivers, - ), + body: CustomScrollView( + controller: scrollController, + physics: const AlwaysScrollableScrollPhysics(), + slivers: slivers, ), ); } @@ -96,8 +96,8 @@ class SliverHeaderItem extends StatefulWidget { ///内容高度 final double contentHeight; - SliverHeaderItem(this.index, - {required this.child, this.headerHeight = 60, this.contentHeight = 120}); + const SliverHeaderItem(this.index, + {super.key, required this.child, this.headerHeight = 60, this.contentHeight = 120}); @override _SliverHeaderItemState createState() => _SliverHeaderItemState(); @@ -114,7 +114,7 @@ class _SliverHeaderItemState extends State super.initState(); ///监听列表改变 - Future.delayed(Duration(seconds: 0), () { + Future.delayed(const Duration(seconds: 0), () { Scrollable.of(context).position.addListener(scrollListener); }); } @@ -125,10 +125,6 @@ class _SliverHeaderItemState extends State super.deactivate(); } - @override - void dispose() { - super.dispose(); - } @override Widget build(BuildContext context) { @@ -167,7 +163,7 @@ class _SliverHeaderItemState extends State return Visibility( visible: (position <= widget.index), - child: new Transform.translate( + child: Transform.translate( offset: Offset(0, -(widget.headerHeight - height)), child: widget.child, ), @@ -225,5 +221,5 @@ class GSYSliverHeaderDelegate extends SliverPersistentHeaderDelegate { FloatingHeaderSnapConfiguration get snapConfiguration => snapConfig; } -typedef Widget Builder( +typedef Builder = Widget Function( BuildContext context, double shrinkOffset, bool overlapsContent); diff --git a/lib/widget/sliver_tab/sliver_tab_child_page.dart b/lib/widget/sliver_tab/sliver_tab_child_page.dart index 7a35993..fdfd6c5 100644 --- a/lib/widget/sliver_tab/sliver_tab_child_page.dart +++ b/lib/widget/sliver_tab/sliver_tab_child_page.dart @@ -4,29 +4,29 @@ import 'package:gsy_flutter_demo/widget/sliver_tab/sliver_tab_sliver.dart'; class SliverTabChildPage extends StatefulWidget { final List pageList; - final tabIndex; + final int tabIndex; - SliverTabChildPage(this.tabIndex, this.pageList); + const SliverTabChildPage(this.tabIndex, this.pageList, {super.key}); @override - _SliverTabChildPageState createState() => _SliverTabChildPageState(); + SliverTabChildPageState createState() => SliverTabChildPageState(); } -class _SliverTabChildPageState extends State +class SliverTabChildPageState extends State with AutomaticKeepAliveClientMixin { - GlobalKey globalKey = new GlobalKey(); + GlobalKey globalKey = GlobalKey(); double initLayoutExtent = 100; double showPullDistance = 150; final double indicatorExtent = 200; final double triggerPullDistance = 300; final ScrollController scrollController = - new ScrollController(initialScrollOffset: -100); + ScrollController(initialScrollOffset: -100); renderListByIndex(tabIndex, pageList) { return CustomScrollView( controller: scrollController, - physics: BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()), + physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()), slivers: [ SliverTabSliver( key: globalKey, diff --git a/lib/widget/sliver_tab/sliver_tab_demo_page3.dart b/lib/widget/sliver_tab/sliver_tab_demo_page3.dart index b2e23e9..15801f1 100644 --- a/lib/widget/sliver_tab/sliver_tab_demo_page3.dart +++ b/lib/widget/sliver_tab/sliver_tab_demo_page3.dart @@ -4,10 +4,12 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:gsy_flutter_demo/widget/sliver_tab/sliver_tab_child_page.dart'; -final kMinHeight = 30.0; +const kMinHeight = 30.0; /// 高级版 Sliver Tab class SliverTabDemoPage3 extends StatefulWidget { + const SliverTabDemoPage3({super.key}); + @override _SliverTabDemoPageState createState() => _SliverTabDemoPageState(); } @@ -16,7 +18,7 @@ class _SliverTabDemoPageState extends State with TickerProviderStateMixin { TabController? tabController; - final PageController pageController = new PageController(); + final PageController pageController = PageController(); final int tabLength = 4; final double tabIconSize = 30; final List dataList = [ @@ -47,9 +49,9 @@ class _SliverTabDemoPageState extends State size: tabIconSize - offset, ), ), - new Expanded( - child: new Center( - child: new Text( + Expanded( + child: Center( + child: Text( "Tab$index", ), ), @@ -67,7 +69,7 @@ class _SliverTabDemoPageState extends State @override void initState() { - tabController = new TabController(length: tabLength, vsync: this); + tabController = TabController(length: tabLength, vsync: this); super.initState(); } @@ -75,9 +77,9 @@ class _SliverTabDemoPageState extends State Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("SliverTabDemoPage3"), + title: const Text("SliverTabDemoPage3"), ), - body: new NotificationListener( + body: NotificationListener( onNotification: (ScrollNotification notification) { if (notification.metrics is PageMetrics) { return false; @@ -144,7 +146,7 @@ class _SliverTabDemoPageState extends State }, ), ), - new Expanded( + Expanded( child: PageView( //physics: NeverScrollableScrollPhysics(), onPageChanged: (index) { @@ -203,5 +205,5 @@ class GSYSliverHeaderDelegate extends SliverPersistentHeaderDelegate { FloatingHeaderSnapConfiguration get snapConfiguration => snapConfig; } -typedef Widget BuilderDelegate( +typedef BuilderDelegate = Widget Function( BuildContext context, double shrinkOffset, bool overlapsContent); diff --git a/lib/widget/sliver_tab/sliver_tab_sliver.dart b/lib/widget/sliver_tab/sliver_tab_sliver.dart index 8614fc9..75eb28b 100644 --- a/lib/widget/sliver_tab/sliver_tab_sliver.dart +++ b/lib/widget/sliver_tab/sliver_tab_sliver.dart @@ -1,18 +1,17 @@ import 'dart:math'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class _SliverTabSliver extends SingleChildRenderObjectWidget { const _SliverTabSliver({ - Key? key, this.containerLayoutExtent = 0.0, this.initLayoutExtent = 0.0, this.hasLayoutExtent = false, this.pinned = false, - Widget? child, - }) : assert(containerLayoutExtent >= 0.0), - super(key: key, child: child); + super.child, + }) : assert(containerLayoutExtent >= 0.0); final double initLayoutExtent; final double containerLayoutExtent; @@ -225,7 +224,7 @@ typedef ContainerBuilder = Widget Function( class SliverTabSliver extends StatefulWidget { const SliverTabSliver({ - Key? key, + super.key, this.triggerPullDistance = _defaultTriggerPullDistance, this.containerExtent = _defaultcontainerExtent, this.initLayoutExtent = 0, @@ -236,8 +235,7 @@ class SliverTabSliver extends StatefulWidget { assert( triggerPullDistance >= containerExtent, 'The container cannot take more space in its final state ' - 'than the amount initially created by overscrolling.'), - super(key: key); + 'than the amount initially created by overscrolling.'); final double triggerPullDistance; @@ -261,19 +259,21 @@ class SliverTabSliver extends StatefulWidget { const Curve opacityCurve = Interval(0.0, 1, curve: Curves.easeInOut); return Stack( children: [ - new Opacity( + Opacity( opacity: 1.0, - child: new Container(color: Colors.red), + child: Container(color: Colors.red), ), - new Opacity( + Opacity( opacity: opacityCurve.transform(min(pulledExtent / containerExtent, 1.0)), child: InkWell( onTap: () { - print("FFFF"); + if (kDebugMode) { + print("FFFF"); + } }, - child: new Container( - decoration: BoxDecoration( + child: Container( + decoration: const BoxDecoration( color: Colors.amber, image: DecorationImage( fit: BoxFit.cover, diff --git a/lib/widget/sliver_tab_demo_page.dart b/lib/widget/sliver_tab_demo_page.dart index 487505a..8941216 100644 --- a/lib/widget/sliver_tab_demo_page.dart +++ b/lib/widget/sliver_tab_demo_page.dart @@ -5,6 +5,8 @@ import 'package:flutter/rendering.dart'; /// 低级版 Sliver Tab,还有 SliverTabDemoPage2 class SliverTabDemoPage extends StatefulWidget { + const SliverTabDemoPage({super.key}); + @override _SliverTabDemoPageState createState() => _SliverTabDemoPageState(); } @@ -13,7 +15,7 @@ class _SliverTabDemoPageState extends State with TickerProviderStateMixin { TabController? tabController; - final ScrollController scrollController = new ScrollController(); + final ScrollController scrollController = ScrollController(); final int tabLength = 4; final double maxHeight = kToolbarHeight; final double minHeight = 30; @@ -37,9 +39,9 @@ class _SliverTabDemoPageState extends State size: tabIconSize - offset, ), ), - new Expanded( - child: new Center( - child: new Text( + Expanded( + child: Center( + child: Text( "Tab$index", ), ), @@ -56,10 +58,10 @@ class _SliverTabDemoPageState extends State delegate: SliverChildBuilderDelegate( (BuildContext context, int index) { return Card( - child: new Container( + child: Container( height: 60, alignment: Alignment.centerLeft, - child: new Text("Tab $indexTab Item $index"), + child: Text("Tab $indexTab Item $index"), ), ); }, @@ -70,7 +72,7 @@ class _SliverTabDemoPageState extends State @override void initState() { - tabController = new TabController(length: tabLength, vsync: this); + tabController = TabController(length: tabLength, vsync: this); super.initState(); } @@ -78,51 +80,49 @@ class _SliverTabDemoPageState extends State Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("SliverTabDemoPage"), + title: const Text("SliverTabDemoPage"), ), - body: new Container( - child: new CustomScrollView( - physics: BouncingScrollPhysics(), - controller: scrollController, - slivers: [ - ///动态放大缩小的tab控件 - SliverPersistentHeader( - pinned: true, - - /// SliverPersistentHeaderDelegate 的实现 - delegate: GSYSliverHeaderDelegate( - maxHeight: maxHeight, - minHeight: minHeight, - changeSize: true, - vSync: this, - snapConfig: FloatingHeaderSnapConfiguration( - curve: Curves.bounceInOut, - duration: const Duration(milliseconds: 10), - ), - builder: (BuildContext context, double shrinkOffset, - bool overlapsContent) { - return Container( - height: maxHeight, - color: Colors.blue, - child: TabBar( - indicatorColor: Colors.cyanAccent, - unselectedLabelColor: Colors.white.withAlpha(100), - labelColor: Colors.cyanAccent, - controller: tabController, - tabs: renderTabs(shrinkOffset), - onTap: (index) { - setState(() {}); - scrollController.animateTo(0, - duration: Duration(milliseconds: 100), - curve: Curves.fastOutSlowIn); - }, - ), - ); - }), - ), - renderListByIndex() - ], - ), + body: CustomScrollView( + physics: const BouncingScrollPhysics(), + controller: scrollController, + slivers: [ + ///动态放大缩小的tab控件 + SliverPersistentHeader( + pinned: true, + + /// SliverPersistentHeaderDelegate 的实现 + delegate: GSYSliverHeaderDelegate( + maxHeight: maxHeight, + minHeight: minHeight, + changeSize: true, + vSync: this, + snapConfig: FloatingHeaderSnapConfiguration( + curve: Curves.bounceInOut, + duration: const Duration(milliseconds: 10), + ), + builder: (BuildContext context, double shrinkOffset, + bool overlapsContent) { + return Container( + height: maxHeight, + color: Colors.blue, + child: TabBar( + indicatorColor: Colors.cyanAccent, + unselectedLabelColor: Colors.white.withAlpha(100), + labelColor: Colors.cyanAccent, + controller: tabController, + tabs: renderTabs(shrinkOffset), + onTap: (index) { + setState(() {}); + scrollController.animateTo(0, + duration: const Duration(milliseconds: 100), + curve: Curves.fastOutSlowIn); + }, + ), + ); + }), + ), + renderListByIndex() + ], ), ); } @@ -175,5 +175,5 @@ class GSYSliverHeaderDelegate extends SliverPersistentHeaderDelegate { FloatingHeaderSnapConfiguration get snapConfiguration => snapConfig; } -typedef Widget Builder( +typedef Builder = Widget Function( BuildContext context, double shrinkOffset, bool overlapsContent); diff --git a/lib/widget/sliver_tab_demo_page2.dart b/lib/widget/sliver_tab_demo_page2.dart index 5578cb0..70dcdaa 100644 --- a/lib/widget/sliver_tab_demo_page2.dart +++ b/lib/widget/sliver_tab_demo_page2.dart @@ -5,6 +5,8 @@ import 'package:flutter/rendering.dart'; /// 高级版 Sliver Tab class SliverTabDemoPage2 extends StatefulWidget { + const SliverTabDemoPage2({super.key}); + @override _SliverTabDemoPageState createState() => _SliverTabDemoPageState(); } @@ -13,8 +15,8 @@ class _SliverTabDemoPageState extends State with TickerProviderStateMixin { TabController? tabController; - final PageController pageController = new PageController(); - final ScrollController scrollController = new ScrollController(); + final PageController pageController = PageController(); + final ScrollController scrollController = ScrollController(); final int tabLength = 4; final double maxHeight = kToolbarHeight; final double minHeight = 30; @@ -38,9 +40,9 @@ class _SliverTabDemoPageState extends State size: tabIconSize - offset, ), ), - new Expanded( - child: new Center( - child: new Text( + Expanded( + child: Center( + child: Text( "Tab$index", ), ), @@ -57,7 +59,7 @@ class _SliverTabDemoPageState extends State child: Builder( builder: (BuildContext context) { return CustomScrollView( - physics: BouncingScrollPhysics(), + physics: const BouncingScrollPhysics(), key: PageStorageKey(tabIndex.toString()), slivers: [ SliverOverlapInjector( @@ -93,7 +95,7 @@ class _SliverTabDemoPageState extends State @override void initState() { - tabController = new TabController(length: tabLength, vsync: this); + tabController = TabController(length: tabLength, vsync: this); super.initState(); } @@ -101,7 +103,7 @@ class _SliverTabDemoPageState extends State Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("SliverTabDemoPage2"), + title: const Text("SliverTabDemoPage2"), ), body: NestedScrollView( controller: scrollController, @@ -134,7 +136,7 @@ class _SliverTabDemoPageState extends State onTap: (index) { setState(() {}); scrollController.animateTo(0, - duration: Duration(milliseconds: 100), + duration: const Duration(milliseconds: 100), curve: Curves.fastOutSlowIn); pageController.jumpToPage(index); }, @@ -204,5 +206,5 @@ class GSYSliverHeaderDelegate extends SliverPersistentHeaderDelegate { FloatingHeaderSnapConfiguration get snapConfiguration => snapConfig; } -typedef Widget BuilderDelegate( +typedef BuilderDelegate = Widget Function( BuildContext context, double shrinkOffset, bool overlapsContent); diff --git a/lib/widget/star_bomb_button_page.dart b/lib/widget/star_bomb_button_page.dart index 7e247be..49fa3d9 100644 --- a/lib/widget/star_bomb_button_page.dart +++ b/lib/widget/star_bomb_button_page.dart @@ -4,15 +4,17 @@ import 'package:flutter/material.dart'; ///以下代码全部来自 ChatGPT 生成,具体详情可见: /// https://juejin.cn/post/7210605626501595195 class StarBombButtonPage extends StatelessWidget { - const StarBombButtonPage({Key? key}) : super(key: key); + const StarBombButtonPage({super.key}); @override Widget build(BuildContext context) { - return YellowStarPage(); + return const YellowStarPage(); } } class YellowStarPage extends StatefulWidget { + const YellowStarPage({super.key}); + @override _YellowStarPageState createState() => _YellowStarPageState(); } @@ -26,7 +28,7 @@ class _YellowStarPageState extends State void initState() { super.initState(); _animationController = - AnimationController(vsync: this, duration: Duration(milliseconds: 500)) + AnimationController(vsync: this, duration: const Duration(milliseconds: 500)) ..addListener(() { setState(() {}); }); @@ -42,7 +44,7 @@ class _YellowStarPageState extends State if (!_isExploded) { _isExploded = true; _animationController.forward(from: 0); - Future.delayed(Duration(milliseconds: 500), () { + Future.delayed(const Duration(milliseconds: 500), () { setState(() { _isExploded = false; }); @@ -54,11 +56,11 @@ class _YellowStarPageState extends State @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar(title: Text('Yellow Star')), + appBar: AppBar(title: const Text('Yellow Star')), body: Center( child: GestureDetector( onTap: _handleStarTap, - child: Container( + child: SizedBox( width: 300, height: 300, child: AnimatedBuilder( diff --git a/lib/widget/statusbar_demo_page.dart b/lib/widget/statusbar_demo_page.dart index 683ae8a..58ad961 100644 --- a/lib/widget/statusbar_demo_page.dart +++ b/lib/widget/statusbar_demo_page.dart @@ -3,6 +3,8 @@ import 'package:flutter/services.dart'; ///状态栏颜色 class StatusBarDemoPage extends StatefulWidget { + const StatusBarDemoPage({super.key}); + @override _StatusBarDemoPageState createState() => _StatusBarDemoPageState(); } @@ -26,49 +28,47 @@ class _StatusBarDemoPageState extends State { getBody() { return Scaffold( - appBar: ImageAppBar(), - body: new Container( - child: Center( - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - new TextButton( - onPressed: () { - ///手动修改 - setState(() { - customSystemUIOverlayStyle = true; - }); - SystemChrome.setSystemUIOverlayStyle( - SystemUiOverlayStyle.light); - }, - style: ButtonStyle( - backgroundColor: ButtonStyleButton.allOrNull( - Colors.yellowAccent, - ), + appBar: const ImageAppBar(), + body: Center( + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + TextButton( + onPressed: () { + ///手动修改 + setState(() { + customSystemUIOverlayStyle = true; + }); + SystemChrome.setSystemUIOverlayStyle( + SystemUiOverlayStyle.light); + }, + style: ButtonStyle( + backgroundColor: ButtonStyleButton.allOrNull( + Colors.yellowAccent, ), - child: new Text("Light"), - ), - new SizedBox( - width: 10, ), - new TextButton( - onPressed: () { - setState(() { - customSystemUIOverlayStyle = true; - }); - SystemChrome.setSystemUIOverlayStyle( - SystemUiOverlayStyle.dark); - }, - style: ButtonStyle( - backgroundColor: ButtonStyleButton.allOrNull( - Colors.greenAccent, - ), + child: const Text("Light"), + ), + const SizedBox( + width: 10, + ), + TextButton( + onPressed: () { + setState(() { + customSystemUIOverlayStyle = true; + }); + SystemChrome.setSystemUIOverlayStyle( + SystemUiOverlayStyle.dark); + }, + style: ButtonStyle( + backgroundColor: ButtonStyleButton.allOrNull( + Colors.greenAccent, ), - child: new Text("Dart"), ), - ], - ), + child: const Text("Dart"), + ), + ], ), ), ); @@ -77,29 +77,30 @@ class _StatusBarDemoPageState extends State { ///自定义 PreferredSizeWidget 做 AppBar class ImageAppBar extends StatelessWidget implements PreferredSizeWidget { + const ImageAppBar({super.key}); + @override Widget build(BuildContext context) { - return Container( - child: Stack( - children: [ - new Image.asset( - "static/gsy_cat.png", - fit: BoxFit.cover, - width: MediaQuery.sizeOf(context).width, - height: kToolbarHeight * 3, - ), - SafeArea( - child: new IconButton( - color: Colors.white, - icon: Icon(Icons.arrow_back_ios), - onPressed: () { - Navigator.of(context).pop(); - }), - ) - ], - ), + return Stack( + children: [ + Image.asset( + "static/gsy_cat.png", + fit: BoxFit.cover, + width: MediaQuery.sizeOf(context).width, + height: kToolbarHeight * 3, + ), + SafeArea( + child: IconButton( + color: Colors.white, + icon: const Icon(Icons.arrow_back_ios), + onPressed: () { + Navigator.of(context).pop(); + }), + ) + ], ); } - Size get preferredSize => Size.fromHeight(kToolbarHeight * 3); + @override + Size get preferredSize => const Size.fromHeight(kToolbarHeight * 3); } diff --git a/lib/widget/stick/stick_demo_page.dart b/lib/widget/stick/stick_demo_page.dart index e63f874..082923c 100644 --- a/lib/widget/stick/stick_demo_page.dart +++ b/lib/widget/stick/stick_demo_page.dart @@ -1,7 +1,10 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:gsy_flutter_demo/widget/stick/stick_widget.dart'; class StickDemoPage extends StatefulWidget { + const StickDemoPage({super.key}); + @override _StickDemoPageState createState() => _StickDemoPageState(); } @@ -11,55 +14,57 @@ class _StickDemoPageState extends State { Widget build(_) { return Scaffold( appBar: AppBar( - title: Text("StickDemoPage"), + title: const Text("StickDemoPage"), ), - body: Container( - child: new ListView.builder( - physics: AlwaysScrollableScrollPhysics(), - itemCount: 100, - itemBuilder: (context, index) { - return new Container( - height: 200, - color: Colors.deepOrange, - child: new StickWidget( - ///header - stickHeader: new Container( - height: 50.0, - color: Colors.deepPurple, - padding: new EdgeInsets.only(left: 10.0), - alignment: Alignment.centerLeft, - child: new InkWell( - onTap: () { + body: ListView.builder( + physics: const AlwaysScrollableScrollPhysics(), + itemCount: 100, + itemBuilder: (context, index) { + return Container( + height: 200, + color: Colors.deepOrange, + child: StickWidget( + ///header + stickHeader: Container( + height: 50.0, + color: Colors.deepPurple, + padding: const EdgeInsets.only(left: 10.0), + alignment: Alignment.centerLeft, + child: InkWell( + onTap: () { + if (kDebugMode) { print("header"); - }, - child: new Text( - '我的 $index 头啊', - style: TextStyle(color: Colors.white), - ), + } + }, + child: Text( + '我的 $index 头啊', + style: const TextStyle(color: Colors.white), ), ), + ), - ///content - stickContent: new InkWell( - onTap: () { + ///content + stickContent: InkWell( + onTap: () { + if (kDebugMode) { print("content"); - }, - child: new Container( - margin: EdgeInsets.only(left: 10), - color: Colors.pinkAccent, - height: 150, - child: new Center( - child: new Text( - '我的$index 内容 啊', - style: TextStyle(color: Colors.white), - ), + } + }, + child: Container( + margin: const EdgeInsets.only(left: 10), + color: Colors.pinkAccent, + height: 150, + child: Center( + child: Text( + '我的$index 内容 啊', + style: const TextStyle(color: Colors.white), ), ), ), ), - ); - }), - ), + ), + ); + }), ); } } diff --git a/lib/widget/stick/stick_demo_page2.dart b/lib/widget/stick/stick_demo_page2.dart index 3eadc37..f1ad722 100644 --- a/lib/widget/stick/stick_demo_page2.dart +++ b/lib/widget/stick/stick_demo_page2.dart @@ -1,11 +1,12 @@ import 'dart:math' as math; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:gsy_flutter_demo/widget/expand/expand_widget.dart'; import 'package:gsy_flutter_demo/widget/stick/stick_widget.dart'; final random = math.Random(); -final stickHeader = 50.0; +const stickHeader = 50.0; ///具备展开和收缩列表能力的Demo class StickExpendDemoPage extends StatefulWidget { @@ -14,6 +15,8 @@ class StickExpendDemoPage extends StatefulWidget { return ExpendedModel(false, List.filled(random.nextInt(20), null)); }); + StickExpendDemoPage({super.key}); + @override _StickExpendDemoPageState createState() => _StickExpendDemoPageState(); } @@ -23,42 +26,41 @@ class _StickExpendDemoPageState extends State { Widget build(_) { return Scaffold( appBar: AppBar( - title: Text("StickExpendDemoPage"), + title: const Text("StickExpendDemoPage"), ), - body: Container( - ///列表数据 - child: new ListView.builder( - physics: AlwaysScrollableScrollPhysics(), - itemCount: widget.tagList.length, - itemBuilder: (context, index) { - return new Container( - color: Colors.white, - - ///头部停靠 - child: new StickWidget( - ///头部 - stickHeader: new Container( - height: stickHeader, - color: Colors.deepPurple, - padding: new EdgeInsets.only(left: 10.0), - alignment: Alignment.centerLeft, - child: new InkWell( - onTap: () { + body: ListView.builder( + physics: const AlwaysScrollableScrollPhysics(), + itemCount: widget.tagList.length, + itemBuilder: (context, index) { + return Container( + color: Colors.white, + + ///头部停靠 + child: StickWidget( + ///头部 + stickHeader: Container( + height: stickHeader, + color: Colors.deepPurple, + padding: const EdgeInsets.only(left: 10.0), + alignment: Alignment.centerLeft, + child: InkWell( + onTap: () { + if (kDebugMode) { print("header"); - }, - child: new Text( - '我的 $index 头啊', - style: TextStyle(color: Colors.white), - ), + } + }, + child: Text( + '我的 $index 头啊', + style: const TextStyle(color: Colors.white), ), ), - - ///可展开内容 - stickContent: ExpandChildList(widget.tagList[index]), ), - ); - }), - ), + + ///可展开内容 + stickContent: ExpandChildList(widget.tagList[index]), + ), + ); + }), ); } } @@ -67,7 +69,7 @@ class _StickExpendDemoPageState extends State { class ExpandChildList extends StatefulWidget { final ExpendedModel expendedModel; - ExpandChildList(this.expendedModel); + const ExpandChildList(this.expendedModel, {super.key}); @override _ExpandChildListState createState() => _ExpandChildListState(); @@ -151,21 +153,20 @@ class ExpandableVisibleContainer extends StatelessWidget { final List dataList; final ExpandedStateChanged? expandedStateChanged; - ExpandableVisibleContainer(this.dataList, + const ExpandableVisibleContainer(this.dataList, {required this.visibleCount, this.itemHeight = 150, this.expandedStateChanged, - key}) - : super(key: key); + super.key}); ///大于可见数量才使用 查看更多 renderExpendedMore(context) { - return new Container( + return Container( height: 50.0, color: Colors.grey, - padding: new EdgeInsets.only(left: 10.0), + padding: const EdgeInsets.only(left: 10.0), alignment: Alignment.center, - child: new InkWell( + child: InkWell( onTap: () { ///展开,回调 ExpandableController.of(context)!.toggle(); @@ -174,7 +175,7 @@ class ExpandableVisibleContainer extends StatelessWidget { child: Container( alignment: Alignment.center, width: MediaQuery.sizeOf(context).width, - child: new Text( + child: const Text( '查看更多', style: TextStyle(color: Colors.black), ), @@ -195,32 +196,32 @@ class ExpandableVisibleContainer extends StatelessWidget { ? visibleCount + 1 : visibleCount; - return new Container( - child: new Align( - alignment: Alignment.centerLeft, - child: Column( - children: List.generate(realVisibleCount, (index) { - ///绘制加载更多按键 - if (index == visibleCount) { - return renderExpendedMore(context); - } - return new InkWell( - onTap: () { + return Align( + alignment: Alignment.centerLeft, + child: Column( + children: List.generate(realVisibleCount, (index) { + ///绘制加载更多按键 + if (index == visibleCount) { + return renderExpendedMore(context); + } + return InkWell( + onTap: () { + if (kDebugMode) { print("content $index"); - }, - child: new Container( - color: Colors.pinkAccent, - height: itemHeight, - child: new Center( - child: new Text( - '我的 $index 内容', - style: TextStyle(color: Colors.white), - ), + } + }, + child: Container( + color: Colors.pinkAccent, + height: itemHeight, + child: Center( + child: Text( + '我的 $index 内容', + style: const TextStyle(color: Colors.white), ), ), - ); - }), - ), + ), + ); + }), ), ); } @@ -233,18 +234,18 @@ class ExpandableContainer extends StatelessWidget { final List dataList; final int visibleCount; - ExpandableContainer(this.dataList, - {required this.visibleCount, + const ExpandableContainer(this.dataList, + {super.key, required this.visibleCount, this.itemHeight = 150, this.expandedStateChanged}); renderMoreItem(context) { - return new Container( + return Container( height: 50.0, color: Colors.grey, - padding: new EdgeInsets.only(left: 10.0), + padding: const EdgeInsets.only(left: 10.0), alignment: Alignment.center, - child: new InkWell( + child: InkWell( onTap: () { ///收起,回调 ExpandableController.of(context)!.toggle(); @@ -253,7 +254,7 @@ class ExpandableContainer extends StatelessWidget { child: Container( alignment: Alignment.center, width: MediaQuery.sizeOf(context).width, - child: new Text( + child: const Text( '收起', style: TextStyle(color: Colors.black), ), @@ -273,23 +274,25 @@ class ExpandableContainer extends StatelessWidget { return Container(); } - return new Column( + return Column( children: List.generate(expandedCount, (index) { ///只有展开后的才需要显示 收起按键 if (index == decCount) { return renderMoreItem(context); } - return new InkWell( + return InkWell( onTap: () { - print("content $index"); + if (kDebugMode) { + print("content $index"); + } }, - child: new Container( + child: Container( color: Colors.pinkAccent, height: itemHeight, - child: new Center( - child: new Text( + child: Center( + child: Text( '我的展开的 $index 内容 啊', - style: TextStyle(color: Colors.white), + style: const TextStyle(color: Colors.white), ), ), ), @@ -299,7 +302,7 @@ class ExpandableContainer extends StatelessWidget { } } -typedef ExpandedStateChanged(bool expanded); +typedef ExpandedStateChanged = Function(bool expanded); class ExpendedModel { bool expended; diff --git a/lib/widget/stick/stick_render.dart b/lib/widget/stick/stick_render.dart index dc68e0f..5cd4920 100644 --- a/lib/widget/stick/stick_render.dart +++ b/lib/widget/stick/stick_render.dart @@ -1,5 +1,6 @@ import 'dart:math' as math; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; @@ -8,7 +9,7 @@ class StickRender extends RenderBox ContainerRenderObjectMixin, RenderBoxContainerDefaultsMixin { StickRender({required ScrollableState? scrollable}) { - this._scrollable = scrollable; + _scrollable = scrollable; } ScrollableState? _scrollable; @@ -35,16 +36,18 @@ class StickRender extends RenderBox try { return localToGlobal(Offset.zero, ancestor: renderObject).dy; } catch (e) { - print(e); + if (kDebugMode) { + print(e); + } } return 0; } @override - void attach(_) { + void attach(owner) { ///设置监听 _scrollable!.position.addListener(markNeedsLayout); - super.attach(_); + super.attach(owner); } @override @@ -86,7 +89,7 @@ class StickRender extends RenderBox void setupParentData(RenderObject child) { super.setupParentData(child); if (child.parentData is! StickParentData) { - child.parentData = new StickParentData(); + child.parentData = StickParentData(); } } @@ -107,11 +110,11 @@ class StickRender extends RenderBox ///对于当前布局,用内容作为宽高 var width = content.size.width; var height = headerHeight + contentHeight; - size = new Size(width, height); + size = Size(width, height); ///内容的初始化位置 (content.parentData as StickParentData).offset = - new Offset(0, headerHeight); + Offset(0, headerHeight); /// 计算出 header 需要的整体偏移量,用于反方向 var headerOffset = height - headerHeight; @@ -122,7 +125,7 @@ class StickRender extends RenderBox ///是滑动的多还是偏移量 var realHeaderOffset = math.min(-scrollAbleDy, headerOffset); (header.parentData as StickParentData).offset = - new Offset(0, math.max(0, realHeaderOffset)); + Offset(0, math.max(0, realHeaderOffset)); } @override diff --git a/lib/widget/stick/stick_widget.dart b/lib/widget/stick/stick_widget.dart index dd4919b..d728a18 100644 --- a/lib/widget/stick/stick_widget.dart +++ b/lib/widget/stick/stick_widget.dart @@ -3,7 +3,7 @@ import 'package:gsy_flutter_demo/widget/stick/stick_render.dart'; class StickWidget extends MultiChildRenderObjectWidget { ///顺序添加 stickHeader 和 stickContent - StickWidget({ + StickWidget({super.key, required stickHeader, required stickContent, }) : super( @@ -14,11 +14,11 @@ class StickWidget extends MultiChildRenderObjectWidget { @override StickRender createRenderObject(BuildContext context) { ///传入 ScrollableState - return new StickRender(scrollable: Scrollable.of(context)); + return StickRender(scrollable: Scrollable.of(context)); } @override void updateRenderObject(BuildContext context, StickRender renderObject) { - renderObject..scrollable = Scrollable.of(context); + renderObject.scrollable = Scrollable.of(context); } } diff --git a/lib/widget/stick_sliver_list_demo_page.dart b/lib/widget/stick_sliver_list_demo_page.dart index 2a6e94e..1310ce8 100644 --- a/lib/widget/stick_sliver_list_demo_page.dart +++ b/lib/widget/stick_sliver_list_demo_page.dart @@ -4,13 +4,15 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; final random = math.Random(); -final stickHeader = 50.0; +const stickHeader = 50.0; class StickSliverListDemoPage extends StatefulWidget { final List dataList = List.generate(7, (index) { return ExpendedModel(false, List.filled(random.nextInt(100), null)); }); + StickSliverListDemoPage({super.key}); + @override _StickSliverListDemoPageState createState() => _StickSliverListDemoPageState(); @@ -20,7 +22,7 @@ class _StickSliverListDemoPageState extends State { int _titleIndex = 0; bool _showTitleTopButton = false; - ScrollController _scrollController = new ScrollController(); + final ScrollController _scrollController = ScrollController(); final GlobalKey scrollKey = GlobalKey(); @@ -37,7 +39,7 @@ class _StickSliverListDemoPageState extends State { } scrollChanged() { - if (widget.dataList.length == 0) { + if (widget.dataList.isEmpty) { return; } var item = widget.dataList.lastWhere((item) { @@ -76,25 +78,23 @@ class _StickSliverListDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("StickSliverListDemoPage"), + title: const Text("StickSliverListDemoPage"), ), - body: new Stack( + body: Stack( children: [ - new Container( - child: CustomScrollView( - key: scrollKey, - controller: _scrollController, - physics: const ClampingScrollPhysics(), - slivers: List.generate(widget.dataList.length, (index) { - return SliverExpandedList( - widget.dataList[index], - "header $index", - valueChanged: (_) { - setState(() {}); - }, - ); - }), - ), + CustomScrollView( + key: scrollKey, + controller: _scrollController, + physics: const ClampingScrollPhysics(), + slivers: List.generate(widget.dataList.length, (index) { + return SliverExpandedList( + widget.dataList[index], + "header $index", + valueChanged: (_) { + setState(() {}); + }, + ); + }), ), StickHeader("header $_titleIndex", showTopButton: _showTitleTopButton, callback: () { @@ -116,8 +116,8 @@ class SliverExpandedList extends StatefulWidget { final int visibleCount; final ValueChanged? valueChanged; - SliverExpandedList(this.expendedModel, this.title, - {this.visibleCount = 3, this.valueChanged}); + const SliverExpandedList(this.expendedModel, this.title, + {super.key, this.visibleCount = 3, this.valueChanged}); @override _SliverExpandedListState createState() => _SliverExpandedListState(); @@ -141,12 +141,12 @@ class _SliverExpandedListState extends State { ///大于可见数量才使用 查看更多 renderExpendedMore() { - return new Container( + return Container( height: 50.0, color: Colors.grey, - padding: new EdgeInsets.only(left: 10.0), + padding: const EdgeInsets.only(left: 10.0), alignment: Alignment.center, - child: new InkWell( + child: InkWell( onTap: () { if (expanded) { ///获取 renderBox @@ -160,9 +160,9 @@ class _SliverExpandedListState extends State { child: Container( alignment: Alignment.center, width: MediaQuery.sizeOf(context).width, - child: new Text( + child: Text( expanded ? "收起" : '查看更多', - style: TextStyle(color: Colors.black), + style: const TextStyle(color: Colors.black), ), ), ), @@ -197,10 +197,10 @@ class _SliverExpandedListState extends State { return StickHeader(widget.title); } return Card( - child: new Container( + child: Container( height: 60, alignment: Alignment.centerLeft, - child: new Text("Item $index"), + child: Text("Item $index"), ), ); }, @@ -215,22 +215,21 @@ class StickHeader extends StatelessWidget { final bool showTopButton; final VoidCallback? callback; - StickHeader(this.title, {Key? key, this.showTopButton = false, this.callback}) - : super(key: key); + const StickHeader(this.title, {super.key, this.showTopButton = false, this.callback}); @override Widget build(BuildContext context) { - return new Container( + return Container( height: stickHeader, color: Colors.deepPurple, - padding: new EdgeInsets.only(left: 10.0), + padding: const EdgeInsets.only(left: 10.0), alignment: Alignment.centerLeft, - child: new Row( + child: Row( children: [ Expanded( - child: new Text( + child: Text( '我的 $title 头啊', - style: TextStyle(color: Colors.white), + style: const TextStyle(color: Colors.white), ), ), Visibility( @@ -239,7 +238,7 @@ class StickHeader extends StatelessWidget { onTap: () { callback?.call(); }, - child: Icon(Icons.vertical_align_top), + child: const Icon(Icons.vertical_align_top), ), ) ], @@ -253,7 +252,7 @@ class ExpendedModel { List dataList; - GlobalKey globalKey = new GlobalKey(); + GlobalKey globalKey = GlobalKey(); ExpendedModel(this.expended, this.dataList); } diff --git a/lib/widget/tag_demo_page.dart b/lib/widget/tag_demo_page.dart index 84dbab5..39ada94 100644 --- a/lib/widget/tag_demo_page.dart +++ b/lib/widget/tag_demo_page.dart @@ -1,19 +1,19 @@ import 'package:flutter/material.dart'; class TagDemoPage extends StatelessWidget { + const TagDemoPage({super.key}); + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("TagDemoPage"), - ), - body: new Container( - child: new Wrap(children: [ - new TagItem("Start"), - for (var item in tags) new TagItem(item), - new TagItem("End"), - ]), + title: const Text("TagDemoPage"), ), + body: Wrap(children: [ + const TagItem("Start"), + for (var item in tags) TagItem(item), + const TagItem("End"), + ]), ); } } @@ -21,17 +21,17 @@ class TagDemoPage extends StatelessWidget { class TagItem extends StatelessWidget { final String text; - TagItem(this.text); + const TagItem(this.text, {super.key}); @override Widget build(BuildContext context) { return Container( - padding: EdgeInsets.symmetric(vertical: 2, horizontal: 5), - margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10), + padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 5), + margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 10), decoration: BoxDecoration( color: Colors.blueAccent.withAlpha(60), - borderRadius: BorderRadius.all(Radius.circular(5))), - child: new Text(text), + borderRadius: const BorderRadius.all(Radius.circular(5))), + child: Text(text), ); } } diff --git a/lib/widget/tear_text_demo_page.dart b/lib/widget/tear_text_demo_page.dart index 42297fc..bf78d25 100644 --- a/lib/widget/tear_text_demo_page.dart +++ b/lib/widget/tear_text_demo_page.dart @@ -7,16 +7,16 @@ import 'package:polygon/polygon.dart'; ///类似 https://codepen.io/mattgrosswork/pen/VwprebG ///内容 讲解 https://juejin.cn/post/7214858677173289017 class TearTextDemoPage extends StatelessWidget { - const TearTextDemoPage({Key? key}) : super(key: key); + const TearTextDemoPage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("TearTextDemoPage"), + title: const Text("TearTextDemoPage"), ), backgroundColor: Colors.black, - body: Center( + body: const Center( child: TearingText(text: "Hello Flutter"), ), ); @@ -26,7 +26,7 @@ class TearTextDemoPage extends StatelessWidget { class TearingText extends StatefulWidget { final String text; - TearingText({required this.text}); + const TearingText({super.key, required this.text}); @override _TearingTextState createState() => _TearingTextState(); @@ -41,10 +41,10 @@ class _TearingTextState extends State { @override void initState() { super.initState(); - timer = Timer.periodic(Duration(milliseconds: 400), (timer) { + timer = Timer.periodic(const Duration(milliseconds: 400), (timer) { tearFunction(); }); - timer2 = Timer.periodic(Duration(milliseconds: 600), (timer) { + timer2 = Timer.periodic(const Duration(milliseconds: 600), (timer) { tearFunction(); }); } @@ -61,7 +61,7 @@ class _TearingTextState extends State { tear = count % 2 == 0; if (tear == true) { setState(() {}); - Future.delayed(Duration(milliseconds: 150), () { + Future.delayed(const Duration(milliseconds: 150), () { setState(() { tear = false; }); @@ -76,6 +76,7 @@ class _TearingTextState extends State { renderMainText(CustomClipper? clipper) { return ClipPath( + clipper: clipper, child: Center( child: Text( widget.text, @@ -86,7 +87,7 @@ class _TearingTextState extends State { ..style = PaintingStyle.fill ..strokeWidth = 5 ..color = Colors.white, - shadows: [ + shadows: const [ Shadow( blurRadius: 10, color: Colors.white, @@ -101,7 +102,6 @@ class _TearingTextState extends State { ), ), ), - clipper: clipper, ); } @@ -109,7 +109,7 @@ class _TearingTextState extends State { return ShaderMask( blendMode: BlendMode.srcATop, shaderCallback: (bounds) { - return LinearGradient( + return const LinearGradient( colors: [Colors.blue, Colors.green, Colors.red], stops: [0.0, 0.5, 1.0], ).createShader(bounds); @@ -119,6 +119,7 @@ class _TearingTextState extends State { transform: Matrix4.translationValues(randomPosition(4), randomPosition(4), 0), child: ClipPath( + clipper: clipper, child: ClipRect( clipper: SizeClipper(top: 30, bottomAspectRatio: 1.5), child: Text( @@ -129,7 +130,7 @@ class _TearingTextState extends State { ..style = PaintingStyle.stroke ..strokeWidth = 5 ..color = Colors.white70, - shadows: [ + shadows: const [ Shadow( blurRadius: 10, color: Colors.white30, @@ -144,7 +145,6 @@ class _TearingTextState extends State { ), ), ), - clipper: clipper, ), ), ); @@ -152,11 +152,12 @@ class _TearingTextState extends State { renderTearText2(CustomClipper? clipper) { return ClipPath( + clipper: clipper, child: Container( alignment: Alignment.center, transform: Matrix4.translationValues( randomPosition(10), randomPosition(10), 0), - padding: EdgeInsets.only(top: 10), + padding: const EdgeInsets.only(top: 10), child: ClipRect( clipper: SizeClipper(top: 20, bottomAspectRatio: 2), child: Text( @@ -168,7 +169,7 @@ class _TearingTextState extends State { ..style = PaintingStyle.stroke ..strokeWidth = 5 ..color = Colors.white30, - shadows: [ + shadows: const [ Shadow( blurRadius: 10, color: Colors.white30, @@ -184,7 +185,6 @@ class _TearingTextState extends State { ), ), ), - clipper: clipper, ); } @@ -227,10 +227,11 @@ class RandomTearingClipper extends CustomClipper { Path getClip(Size size) { var points = generatePoint(); var polygon = Polygon(points); - if (tear) + if (tear) { return polygon.computePath(rect: Offset.zero & size); - else + } else { return Path()..addRect(Offset.zero & size); + } } @override @@ -245,7 +246,7 @@ class SizeClipper extends CustomClipper { @override Rect getClip(Size size) { - return new Rect.fromLTWH( + return Rect.fromLTWH( 0.0, top, size.width, size.height / bottomAspectRatio); } diff --git a/lib/widget/test_center_sliver/test_center_sliver.dart b/lib/widget/test_center_sliver/test_center_sliver.dart index cd2a478..a9d5bf7 100644 --- a/lib/widget/test_center_sliver/test_center_sliver.dart +++ b/lib/widget/test_center_sliver/test_center_sliver.dart @@ -1,18 +1,17 @@ import 'dart:math'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; class _TestCenterSliver extends SingleChildRenderObjectWidget { const _TestCenterSliver({ - Key? key, this.containerLayoutExtent = 0.0, this.initLayoutExtent = 0.0, this.hasLayoutExtent = false, this.pinned = false, - Widget? child, - }) : assert(containerLayoutExtent >= 0.0), - super(key: key, child: child); + super.child, + }) : assert(containerLayoutExtent >= 0.0); final double initLayoutExtent; final double containerLayoutExtent; @@ -122,7 +121,7 @@ class _RenderCustomSliver extends RenderSliver ///布局没有发生变化,滚动 final bool active = constraints.overlap < 0.0 || layoutExtent > 0.0; - final double overscrolledExtent = 0.0; + const double overscrolledExtent = 0.0; child!.layout( constraints.asBoxConstraints( @@ -222,7 +221,7 @@ typedef ContainerBuilder = Widget Function( class TestCenterSliver extends StatefulWidget { const TestCenterSliver({ - Key? key, + super.key, this.triggerPullDistance = _defaultTriggerPullDistance, this.containerExtent = _defaultcontainerExtent, this.initLayoutExtent = 0, @@ -233,8 +232,7 @@ class TestCenterSliver extends StatefulWidget { assert( triggerPullDistance >= containerExtent, 'The container cannot take more space in its final state ' - 'than the amount initially created by overscrolling.'), - super(key: key); + 'than the amount initially created by overscrolling.'); final double triggerPullDistance; @@ -258,19 +256,21 @@ class TestCenterSliver extends StatefulWidget { const Curve opacityCurve = Interval(0.0, 1, curve: Curves.easeInOut); return Stack( children: [ - new Opacity( + Opacity( opacity: 1.0, - child: new Container(color: Colors.red), + child: Container(color: Colors.red), ), - new Opacity( + Opacity( opacity: opacityCurve.transform(min(pulledExtent / containerExtent, 1.0)), child: InkWell( onTap: () { - print("FFFF"); + if (kDebugMode) { + print("FFFF"); + } }, - child: new Container( - decoration: BoxDecoration( + child: Container( + decoration: const BoxDecoration( color: Colors.amber, image: DecorationImage( fit: BoxFit.cover, diff --git a/lib/widget/test_center_sliver/test_center_sliver_page.dart b/lib/widget/test_center_sliver/test_center_sliver_page.dart index cf3c86e..755dcdc 100644 --- a/lib/widget/test_center_sliver/test_center_sliver_page.dart +++ b/lib/widget/test_center_sliver/test_center_sliver_page.dart @@ -3,6 +3,8 @@ import 'package:gsy_flutter_demo/widget/test_center_sliver/test_center_sliver.da class TestCenterSliverPage extends StatefulWidget { + const TestCenterSliverPage({super.key}); + @override TestCenterSliverPageState createState() => TestCenterSliverPageState(); } @@ -14,24 +16,22 @@ class TestCenterSliverPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("TestCenterSliverPage"), + title: const Text("TestCenterSliverPage"), ), - body: Container( - child: CustomScrollView( - anchor: 0.5, - ///回弹效果 - physics: const BouncingScrollPhysics( - parent: AlwaysScrollableScrollPhysics()), - slivers: [ - TestCenterSliver( - initLayoutExtent: 100, - containerExtent: 100, - triggerPullDistance: 100, - pinned: false, - ), + body: const CustomScrollView( + anchor: 0.5, + ///回弹效果 + physics: BouncingScrollPhysics( + parent: AlwaysScrollableScrollPhysics()), + slivers: [ + TestCenterSliver( + initLayoutExtent: 100, + containerExtent: 100, + triggerPullDistance: 100, + pinned: false, + ), - ], - ), + ], ), ); } diff --git a/lib/widget/text_line_height_demo_page.dart b/lib/widget/text_line_height_demo_page.dart index af46a3a..d4cab1d 100644 --- a/lib/widget/text_line_height_demo_page.dart +++ b/lib/widget/text_line_height_demo_page.dart @@ -9,20 +9,22 @@ class TextLineHeightDemoPage extends StatelessWidget { final double fontSize = 16; + const TextLineHeightDemoPage({super.key}); + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("TextLineHeightDemoPage"), + title: const Text("TextLineHeightDemoPage"), ), body: Container( color: Colors.blueGrey, - margin: EdgeInsets.all(20), + margin: const EdgeInsets.all(20), ///利用 Transform 偏移将对应权重部分位置 child: Transform.translate( offset: Offset(0, -fontSize * leading / 2), - child: new Text( + child: Text( textContent, strutStyle: StrutStyle(forceStrutHeight: true, height: 1, leading: leading), diff --git a/lib/widget/text_size_demo_page.dart b/lib/widget/text_size_demo_page.dart index 85c1ea4..d0aa589 100644 --- a/lib/widget/text_size_demo_page.dart +++ b/lib/widget/text_size_demo_page.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; class TextSizeDemoPage extends StatefulWidget { + const TextSizeDemoPage({super.key}); + @override _TextSizeDemoPageState createState() => _TextSizeDemoPageState(); } @@ -22,28 +24,28 @@ class _TextSizeDemoPageState extends State { .copyWith(textScaler: textScaler), child: Scaffold( appBar: AppBar( - title: new Text("TextLineHeightDemoPage"), + title: const Text("TextLineHeightDemoPage"), ), - body: new Stack( + body: Stack( children: [ Container( color: Colors.blueGrey, - margin: EdgeInsets.all(20), + margin: const EdgeInsets.all(20), ///利用 Transform 偏移将对应权重部分位置 - child: new Text( + child: const Text( textContent, style: TextStyle(color: Colors.black), ), ), - new Align( + Align( alignment: Alignment.bottomCenter, - child: new Padding( - padding: EdgeInsets.only(bottom: 50), - child: new Row( + child: Padding( + padding: const EdgeInsets.only(bottom: 50), + child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ - new TextButton( + TextButton( onPressed: () { if (scale > 1) { setState(() { @@ -54,12 +56,12 @@ class _TextSizeDemoPageState extends State { }, style: TextButton.styleFrom( backgroundColor: Colors.redAccent), - child: new Text("-"), + child: const Text("-"), ), - new SizedBox( + const SizedBox( width: 10, ), - new TextButton( + TextButton( onPressed: () { setState(() { textScaler.scale(scale + 1); @@ -68,7 +70,7 @@ class _TextSizeDemoPageState extends State { }, style: TextButton.styleFrom( backgroundColor: Colors.greenAccent), - child: new Text("+"), + child: const Text("+"), ) ], ), diff --git a/lib/widget/tick_click_demo_page.dart b/lib/widget/tick_click_demo_page.dart index 936f628..9d5990e 100644 --- a/lib/widget/tick_click_demo_page.dart +++ b/lib/widget/tick_click_demo_page.dart @@ -5,6 +5,8 @@ import 'dart:math' as math; import 'package:flutter/material.dart'; class TickClickDemoPage extends StatefulWidget { + const TickClickDemoPage({super.key}); + @override _TickClickPageState createState() => _TickClickPageState(); } @@ -21,7 +23,7 @@ class _TickClickPageState extends State void initState() { super.initState(); controller = - new AnimationController(vsync: this, duration: Duration(seconds: 59)); + AnimationController(vsync: this, duration: const Duration(seconds: 59)); animation = Tween(begin: 60.0, end: 1.0).animate(controller) ..addListener(() { if (animation!.value.toInt() != value) { @@ -43,20 +45,18 @@ class _TickClickPageState extends State Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("TickClickDemoPage"), + title: const Text("TickClickDemoPage"), ), ///用封装好的 Transition 做动画 - body: new Container( - child: Center( - child: new Container( - height: MediaQuery.sizeOf(context).width, - width: MediaQuery.sizeOf(context).width, - color: Colors.greenAccent, - child: CustomPaint( - ///直接使用值做动画 - foregroundPainter: _ClickAnimationPainter(animation), - ), + body: Center( + child: Container( + height: MediaQuery.sizeOf(context).width, + width: MediaQuery.sizeOf(context).width, + color: Colors.greenAccent, + child: CustomPaint( + ///直接使用值做动画 + foregroundPainter: _ClickAnimationPainter(animation), ), ), ), @@ -105,6 +105,7 @@ class _ClickAnimationPainter extends CustomPainter { if (Platform.isAndroid == true || Platform.isIOS == true) { canvas.drawColor(Colors.black, BlendMode.clear); } + // ignore: empty_catches } catch (e) {} canvas.save(); canvas.translate(paintWidth / 2, paintHeight / 2); @@ -163,7 +164,7 @@ class _ClickAnimationPainter extends CustomPainter { String minute = ((dateTime.minute) < 10) ? "0${(dateTime.minute)}" : dateTime.minute.toString(); - drawText(canvas, "$hour:$minute", Color(0xFFFFFFFF), textSize, + drawText(canvas, "$hour:$minute", const Color(0xFFFFFFFF), textSize, Offset(-textSize / 2, -textSize / 3), fontSize: hourRadius * 0.4); @@ -173,7 +174,7 @@ class _ClickAnimationPainter extends CustomPainter { : (dateTime.month + 1).toString(); String day = dateTime.day.toString(); String dayOfWeek = dateTime.weekday.toString(); - drawText(canvas, "$month.$day 星期$dayOfWeek", Color(0xFFFFFFFF), textSize, + drawText(canvas, "$month.$day 星期$dayOfWeek", const Color(0xFFFFFFFF), textSize, Offset(-textSize / 2, 20), fontSize: hourRadius * 0.16); } diff --git a/lib/widget/transform_canvas_demo_page.dart b/lib/widget/transform_canvas_demo_page.dart index dd2e660..19bbdbd 100644 --- a/lib/widget/transform_canvas_demo_page.dart +++ b/lib/widget/transform_canvas_demo_page.dart @@ -3,6 +3,8 @@ import 'dart:math' as math; import 'package:flutter/material.dart'; class TransformCanvasDemoPage extends StatefulWidget { + const TransformCanvasDemoPage({super.key}); + @override _TransformCanvasDemoPageState createState() => _TransformCanvasDemoPageState(); @@ -15,7 +17,7 @@ class _TransformCanvasDemoPageState extends State { @override void initState() { super.initState(); - timer = Timer.periodic(Duration(milliseconds: 300), (_) { + timer = Timer.periodic(const Duration(milliseconds: 300), (_) { setState(() { angle = angle + math.pi / 10; }); @@ -32,12 +34,12 @@ class _TransformCanvasDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("TransformCanvasDemoPage"), + title: const Text("TransformCanvasDemoPage"), ), - body: new Container( + body: Container( alignment: Alignment.center, child: Center( - child: new Container( + child: SizedBox( height: 200, width: 200, child: CustomPaint( @@ -51,7 +53,7 @@ class _TransformCanvasDemoPageState extends State { } class _AnimationPainter extends CustomPainter { - Paint _paint = new Paint(); + final Paint _paint = Paint(); double angle; _AnimationPainter(this.angle); @@ -125,7 +127,7 @@ class _AnimationPainter extends CustomPainter { renderPath(double angleX, double angleY, Canvas canvas, [double positionX = 0, double positionY = 0]) { - Path path = new Path(); + Path path = Path(); var t = Matrix4.identity()..rotateX(angleX)..rotateY(angleY); t.leftTranslate(positionX, positionY); t.translate(-positionX, -positionY); diff --git a/lib/widget/transform_demo_page.dart b/lib/widget/transform_demo_page.dart index 4909067..639276b 100644 --- a/lib/widget/transform_demo_page.dart +++ b/lib/widget/transform_demo_page.dart @@ -1,13 +1,15 @@ import 'package:flutter/material.dart'; class TransformDemoPage extends StatelessWidget { + const TransformDemoPage({super.key}); + ///头像 getHeader(context) { ///向上偏移 -30 位置 return Transform.translate( - offset: Offset(0, -30), - child: new Container( + offset: const Offset(0, -30), + child: Container( width: 72.0, height: 72.0, decoration: BoxDecoration( @@ -20,7 +22,7 @@ class TransformDemoPage extends StatelessWidget { shape: BoxShape.circle, ///图片 - image: DecorationImage( + image: const DecorationImage( fit: BoxFit.cover, image: AssetImage( "static/gsy_cat.png", @@ -38,20 +40,20 @@ class TransformDemoPage extends StatelessWidget { return Scaffold( backgroundColor: Theme.of(context).primaryColorDark, appBar: AppBar( - title: new Text("TransformDemoPage"), + title: const Text("TransformDemoPage"), ), body: Container( alignment: Alignment.center, - child: new Card( - margin: EdgeInsets.all(10), + child: Card( + margin: const EdgeInsets.all(10), child: Container( height: 150, - padding: EdgeInsets.all(10), - child: new Column( + padding: const EdgeInsets.all(10), + child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ getHeader(context), - new Text( + const Text( "Flutter is Google's portable UI toolkit for crafting " "beautiful, natively compiled applications for mobile, " "web, and desktop from a single codebase. ", diff --git a/lib/widget/un_bounded_listview.dart b/lib/widget/un_bounded_listview.dart index f64437f..0faea14 100644 --- a/lib/widget/un_bounded_listview.dart +++ b/lib/widget/un_bounded_listview.dart @@ -6,7 +6,7 @@ import 'package:flutter/rendering.dart'; ///介绍链接 https://juejin.cn/post/7225891176531951677 class UnboundedListViewDemoPage extends StatefulWidget { - const UnboundedListViewDemoPage({Key? key}) : super(key: key); + const UnboundedListViewDemoPage({super.key}); @override State createState() => @@ -33,7 +33,7 @@ class _UnboundedListViewDemoPageState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("UnboundedListViewDemoPage"), + title: const Text("UnboundedListViewDemoPage"), ), extendBody: true, body: Container( @@ -46,7 +46,7 @@ class _UnboundedListViewDemoPageState extends State { child: Row( children: List.generate(50, (index) { return Padding( - padding: EdgeInsets.all(2), + padding: const EdgeInsets.all(2), child: Container( alignment: Alignment.bottomCenter, color: Colors.blue, @@ -64,9 +64,11 @@ class _UnboundedListViewDemoPageState extends State { scrollDirection: Axis.horizontal, itemCount: 100, itemBuilder: (context, index) { - print('$index'); + if (kDebugMode) { + print('$index'); + } return Padding( - padding: EdgeInsets.all(2), + padding: const EdgeInsets.all(2), child: Container( height: index * 1.0 + 10, width: 50, @@ -133,6 +135,7 @@ mixin UnboundedListViewMixin on ListView { return UnboundedSliverList(delegate: childrenDelegate); } + @override @protected Widget buildViewport( BuildContext context, @@ -184,9 +187,10 @@ mixin UnboundedListViewMixin on ListView { } } - if (effectivePadding != null) + if (effectivePadding != null) { sliver = UnboundedSliverPadding(padding: effectivePadding, sliver: sliver); + } return [sliver]; } } @@ -234,8 +238,8 @@ mixin UnboundedSliverListMixin on SliverList { class UnboundedRenderSliverList extends RenderSliverList { UnboundedRenderSliverList({ - required RenderSliverBoxChildManager childManager, - }) : super(childManager: childManager); + required super.childManager, + }); // See RenderSliverList::performLayout @override @@ -590,8 +594,9 @@ class UnboundedRenderSliverList extends RenderSliverList { // We may have started the layout while scrolled to the end, which would not // expose a new child. - if (estimatedMaxScrollOffset == endScrollOffset) + if (estimatedMaxScrollOffset == endScrollOffset) { childManager.setDidUnderflow(true); + } childManager.didFinishLayout(); } } @@ -654,7 +659,7 @@ mixin UnboundedRenderViewportMixin on RenderViewport { required double mainAxisExtent, required double crossAxisExtent, required GrowthDirection growthDirection, - required RenderSliver? advance(RenderSliver child), + required RenderSliver? Function(RenderSliver child) advance, required double remainingCacheExtent, required double cacheOrigin, }) { diff --git a/lib/widget/verification_code_input_demo_page.dart b/lib/widget/verification_code_input_demo_page.dart index aa9d90a..1917d23 100644 --- a/lib/widget/verification_code_input_demo_page.dart +++ b/lib/widget/verification_code_input_demo_page.dart @@ -5,33 +5,32 @@ import 'package:flutter/services.dart'; ///验证码输入框 class VerificationCodeInputDemoPage extends StatelessWidget { + const VerificationCodeInputDemoPage({super.key}); + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("VerificationCodeInputDemoPage"), + title: const Text("VerificationCodeInputDemoPage"), ), - body: new GestureDetector( + body: GestureDetector( behavior: HitTestBehavior.translucent, onTap: () { - FocusScope.of(context).requestFocus(new FocusNode()); + FocusScope.of(context).requestFocus(FocusNode()); }, - child: Container( - child: new Center( - child: VerCodeInput( - ctx: context, - length: 6, - keyboardType: TextInputType.number, - builder: staticRectangle(context), - onChanged: (value) { - print(value); - }, - - ///输入完成时 - onFilled: (value) { - //print('Your input is $value.'); - }, - ), + child: Center( + child: VerCodeInput( + ctx: context, + length: 6, + keyboardType: TextInputType.number, + builder: staticRectangle(context), + onChanged: (value) { + }, + + ///输入完成时 + onFilled: (value) { + //print('Your input is $value.'); + }, ), ), ), @@ -64,7 +63,7 @@ typedef CodeInputBuilder = Widget Function(bool hasFocus, String char); class VerCodeInput extends StatefulWidget { const VerCodeInput._({ - Key? key, + super.key, required this.length, required this.keyboardType, required this.inputFormatters, @@ -72,7 +71,7 @@ class VerCodeInput extends StatefulWidget { required this.ctx, this.onChanged, this.onFilled, - }) : super(key: key); + }); factory VerCodeInput({ Key? key, @@ -190,7 +189,7 @@ class _VerCodeInputState extends State { return Stack(children: [ // This is the actual EditableText wrapped in a Container with zero // dimensions. - Container( + SizedBox( width: 0.0, height: 0.0, child: EditableText( @@ -199,7 +198,7 @@ class _VerCodeInputState extends State { inputFormatters: widget.inputFormatters, keyboardType: widget.keyboardType, backgroundCursorColor: Colors.black, - style: TextStyle(), + style: const TextStyle(), // Doesn't really matter. cursorColor: Colors.black, // Doesn't really matter. @@ -267,7 +266,7 @@ abstract class CodeInputBuilders { height: totalSize.height, alignment: Alignment.center, child: AnimatedContainer( - duration: Duration(milliseconds: 100), + duration: const Duration(milliseconds: 100), decoration: char.isEmpty ? emptyDecoration : filledDecoration, width: char.isEmpty ? emptySize.width : filledSize.width, height: char.isEmpty ? emptySize.height : filledSize.height, @@ -339,7 +338,7 @@ abstract class CodeInputBuilders { filledRadius: filledRadius, border: Border.all(color: Colors.white, width: 2.0), color: Colors.white10, - textStyle: TextStyle( + textStyle: const TextStyle( color: Colors.white, fontSize: 20.0, fontWeight: FontWeight.bold)); } @@ -355,7 +354,7 @@ abstract class CodeInputBuilders { filledRadius: filledRadius, border: Border.all(color: Colors.black, width: 2.0), color: Colors.black12, - textStyle: TextStyle( + textStyle: const TextStyle( color: Colors.black, fontSize: 20.0, fontWeight: FontWeight.bold)); } @@ -373,7 +372,7 @@ abstract class CodeInputBuilders { borderRadius: borderRadius, border: Border.all(color: Colors.white, width: 2.0), color: Colors.white10, - textStyle: TextStyle( + textStyle: const TextStyle( color: Colors.white, fontSize: 20.0, fontWeight: FontWeight.bold)); } @@ -390,7 +389,7 @@ abstract class CodeInputBuilders { borderRadius: borderRadius, border: Border.all(color: Colors.white, width: 1.0), color: Colors.transparent, - textStyle: TextStyle( + textStyle: const TextStyle( color: Colors.white, fontSize: 20.0, fontWeight: FontWeight.bold)); } @@ -408,7 +407,7 @@ abstract class CodeInputBuilders { borderRadius: borderRadius, border: Border.all(color: Colors.black, width: 2.0), color: Colors.black12, - textStyle: TextStyle( + textStyle: const TextStyle( color: Colors.black, fontSize: 20.0, fontWeight: FontWeight.bold)); } } diff --git a/lib/widget/verification_code_input_demo_page2.dart b/lib/widget/verification_code_input_demo_page2.dart index 972d43a..3198ff9 100644 --- a/lib/widget/verification_code_input_demo_page2.dart +++ b/lib/widget/verification_code_input_demo_page2.dart @@ -5,6 +5,8 @@ import 'package:flutter/services.dart'; ///验证码输入框 class VerificationCodeInputDemoPage2 extends StatefulWidget { + const VerificationCodeInputDemoPage2({super.key}); + @override _VerificationCodeInputDemoPage2State createState() => _VerificationCodeInputDemoPage2State(); @@ -12,19 +14,19 @@ class VerificationCodeInputDemoPage2 extends StatefulWidget { class _VerificationCodeInputDemoPage2State extends State { - var focusNode = new FocusNode(); + var focusNode = FocusNode(); var textEditingController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("VerificationCodeInputDemoPage"), + title: const Text("VerificationCodeInputDemoPage"), ), - body: new GestureDetector( + body: GestureDetector( behavior: HitTestBehavior.translucent, onTap: () { - FocusScope.of(context).requestFocus(new FocusNode()); + FocusScope.of(context).requestFocus(FocusNode()); }, child: Container( alignment: Alignment.center, @@ -51,13 +53,13 @@ class PINInputWidget extends StatelessWidget { final void Function(String value)? onFilled; - final GlobalKey tipGlobalKey = new GlobalKey(); + final GlobalKey tipGlobalKey = GlobalKey(); final TextEditingController? textEditingController; final FocusNode? node; final EdgeInsetsGeometry? margin; PINInputWidget( - {this.title = "", + {super.key, this.title = "", this.tipTitle, this.onChanged, this.onFilled, @@ -72,29 +74,29 @@ class PINInputWidget extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ - new Container( - margin: margin ?? EdgeInsets.only(left: 50, right: 50), - child: new Row( + Container( + margin: margin ?? const EdgeInsets.only(left: 50, right: 50), + child: Row( children: [ Text( title, - style: TextStyle( + style: const TextStyle( color: Colors.black, fontSize: 16, fontWeight: FontWeight.bold), ), - new Expanded(child: new Container()), + Expanded(child: Container()), if (needTip) Text(tipTitle!, - style: TextStyle( + style: const TextStyle( color: Colors.black, fontSize: 16, )), ], ), ), - new Container( - margin: EdgeInsets.only(top: 5), + Container( + margin: const EdgeInsets.only(top: 5), child: VerCodeInput( controller: textEditingController, length: 6, @@ -106,7 +108,7 @@ class PINInputWidget extends StatelessWidget { ///输入完成时 onFilled: onFilled ?? (value) { - FocusScope.of(context).requestFocus(new FocusNode()); + FocusScope.of(context).requestFocus(FocusNode()); }, ), ) @@ -127,7 +129,7 @@ CodeInputBuilder pinRectangle(BuildContext context, double width = MediaQuery.sizeOf(context).width; double codeFullSize = ((width - 2 * padding) / codeSize); double codeNormalSize = codeFullSize; - final textStyle = + const textStyle = TextStyle(color: Colors.black, fontSize: 18, fontWeight: FontWeight.bold); return _pinContainerized( totalSize: Size(codeFullSize, codeFullSize), @@ -147,13 +149,13 @@ CodeInputBuilder _pinContainerized( required TextStyle emptyTextStyle, required TextStyle filledTextStyle, required Color color}) { - final width = 0.5; - final borderRadiusSize = Radius.circular(4); + const width = 0.5; + const borderRadiusSize = Radius.circular(4); - final borderColor = Color.fromARGB(255, 151, 151, 151); + const borderColor = Color.fromARGB(255, 151, 151, 151); final decoration = BoxDecoration( - border: Border( + border: const Border( top: BorderSide(width: width, color: borderColor), left: BorderSide(width: width, color: borderColor), right: BorderSide.none, @@ -164,7 +166,7 @@ CodeInputBuilder _pinContainerized( ///因为有 borderRadius 的不能 BorderSide 不同 final decorationSecond = BoxDecoration( - border: Border( + border: const Border( top: BorderSide(width: width, color: borderColor), left: BorderSide.none, right: BorderSide.none, @@ -175,26 +177,26 @@ CodeInputBuilder _pinContainerized( ///开始带弧度的 border final decorationStart = BoxDecoration( - border: Border( + border: const Border( top: BorderSide(width: width, color: borderColor), left: BorderSide(width: width, color: borderColor), right: BorderSide(width: width, color: borderColor), bottom: BorderSide(width: width, color: borderColor), ), - borderRadius: BorderRadius.only( + borderRadius: const BorderRadius.only( topLeft: borderRadiusSize, bottomLeft: borderRadiusSize), color: color, ); ///结束带弧度的 border final decorationEnd = BoxDecoration( - border: Border( + border: const Border( top: BorderSide(width: width, color: borderColor), left: BorderSide(width: width, color: borderColor), right: BorderSide(width: width, color: borderColor), bottom: BorderSide(width: width, color: borderColor), ), - borderRadius: BorderRadius.only( + borderRadius: const BorderRadius.only( topRight: borderRadiusSize, bottomRight: borderRadiusSize), color: color, ); @@ -215,7 +217,7 @@ CodeInputBuilder _pinContainerized( height: totalSize.height, alignment: Alignment.center, child: AnimatedContainer( - duration: Duration(milliseconds: 100), + duration: const Duration(milliseconds: 100), decoration: getDecoration(index), width: char.isEmpty ? emptySize.width : filledSize.width, height: char.isEmpty ? emptySize.height : filledSize.height, @@ -241,21 +243,21 @@ CodeInputBuilder pinLine(BuildContext context) { bottom: BorderSide(color: Theme.of(context).primaryColor, width: 0.5)), color: Colors.transparent, - textStyle: TextStyle( + textStyle: const TextStyle( color: Colors.black, fontSize: 16.0, fontWeight: FontWeight.bold)); } renderTipIcon(BuildContext context, String title, GlobalKey key, {expanded = true, double? width, bool needIcon = true}) { - var titleWidget = new Container( + var titleWidget = Container( alignment: Alignment.centerLeft, - child: new RichText( - text: new TextSpan( - style: TextStyle( + child: RichText( + text: TextSpan( + style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black), text: title, - children: [ - new TextSpan( + children: const [ + TextSpan( style: TextStyle( color: Colors.black, fontSize: 15, @@ -266,12 +268,12 @@ renderTipIcon(BuildContext context, String title, GlobalKey key, if (!needIcon) { return titleWidget; } - return new Row( + return Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.start, children: [ titleWidget, - new Container( + Container( alignment: Alignment.topLeft, child: InkWell( onTap: () { @@ -283,7 +285,7 @@ renderTipIcon(BuildContext context, String title, GlobalKey key, // Offset offset = renderBoxRed.localToGlobal(Offset.zero); // showPasswordTip(context, offset.dx + 7, offset.dy - top + 14); }, - child: new Icon( + child: Icon( Icons.error, key: key, color: Colors.black, @@ -319,7 +321,7 @@ class UpWhitelistingTextInputFormatter extends TextInputFormatter { .allMatches(substring.toUpperCase()) .map((Match match) => match.group(0)) .join(); - if (result.length > 0) { + if (result.isNotEmpty) { return result; } return ""; @@ -334,10 +336,10 @@ class UpWhitelistingTextInputFormatter extends TextInputFormatter { TextEditingValue _selectionAwareTextManipulation( TextEditingValue old, TextEditingValue value, - String substringManipulation(String substring), + String Function(String substring) substringManipulation, ) { - if (value.text.length != 0 && - substringManipulation(value.text).length == 0) { + if (value.text.isNotEmpty && + substringManipulation(value.text).isEmpty) { return old; } final int selectionStartIndex = value.selection.baseOffset; @@ -381,7 +383,7 @@ typedef CodeInputBuilder = Widget Function( class VerCodeInput extends StatefulWidget { const VerCodeInput._({ - Key? key, + super.key, required this.length, required this.keyboardType, required this.inputFormatters, @@ -390,7 +392,7 @@ class VerCodeInput extends StatefulWidget { this.controller, this.onFilled, this.node, - }) : super(key: key); + }); factory VerCodeInput({ Key? key, @@ -519,7 +521,7 @@ class _VerCodeInputState extends State { return Stack(children: [ // This is the actual EditableText wrapped in a Container with zero // dimensions. - Container( + SizedBox( width: 0.0, height: 0.0, child: EditableText( @@ -528,7 +530,7 @@ class _VerCodeInputState extends State { inputFormatters: widget.inputFormatters, keyboardType: widget.keyboardType, backgroundCursorColor: Colors.black, - style: TextStyle(), + style: const TextStyle(), // Doesn't really matter. cursorColor: Colors.black, // Doesn't really matter. @@ -593,7 +595,7 @@ abstract class CodeInputBuilders { height: totalSize.height, alignment: alignment, child: AnimatedContainer( - duration: Duration(milliseconds: 100), + duration: const Duration(milliseconds: 100), decoration: char.isEmpty ? emptyDecoration : filledDecoration, width: char.isEmpty ? emptySize.width : filledSize.width, height: char.isEmpty ? emptySize.height : filledSize.height, @@ -667,7 +669,7 @@ abstract class CodeInputBuilders { filledRadius: filledRadius, border: Border.all(color: Colors.white, width: 2.0), color: Colors.white10, - textStyle: TextStyle( + textStyle: const TextStyle( color: Colors.white, fontSize: 20.0, fontWeight: FontWeight.bold)); } @@ -683,7 +685,7 @@ abstract class CodeInputBuilders { filledRadius: filledRadius, border: Border.all(color: Colors.black, width: 2.0), color: Colors.black12, - textStyle: TextStyle( + textStyle: const TextStyle( color: Colors.black, fontSize: 20.0, fontWeight: FontWeight.bold)); } @@ -701,7 +703,7 @@ abstract class CodeInputBuilders { borderRadius: borderRadius, border: Border.all(color: Colors.white, width: 2.0), color: Colors.white10, - textStyle: TextStyle( + textStyle: const TextStyle( color: Colors.white, fontSize: 20.0, fontWeight: FontWeight.bold)); } @@ -718,7 +720,7 @@ abstract class CodeInputBuilders { borderRadius: borderRadius, border: Border.all(color: Colors.white, width: 1.0), color: Colors.transparent, - textStyle: TextStyle( + textStyle: const TextStyle( color: Colors.white, fontSize: 20.0, fontWeight: FontWeight.bold)); } @@ -736,7 +738,7 @@ abstract class CodeInputBuilders { borderRadius: borderRadius, border: Border.all(color: Colors.black, width: 2.0), color: Colors.black12, - textStyle: TextStyle( + textStyle: const TextStyle( color: Colors.black, fontSize: 20.0, fontWeight: FontWeight.bold)); } } diff --git a/lib/widget/viewpager_demo_page.dart b/lib/widget/viewpager_demo_page.dart index 07134db..a45d23c 100644 --- a/lib/widget/viewpager_demo_page.dart +++ b/lib/widget/viewpager_demo_page.dart @@ -10,12 +10,14 @@ class ViewPagerDemoPage extends StatelessWidget { Colors.greenAccent ]; + ViewPagerDemoPage({super.key}); + @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Theme.of(context).primaryColorDark, appBar: AppBar( - title: new Text("ViewPagerDemoPage"), + title: const Text("ViewPagerDemoPage"), ), body: Container( alignment: Alignment.topCenter, @@ -24,19 +26,19 @@ class ViewPagerDemoPage extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.max, children: [ - new Expanded( - child: new TransformerPageView( + Expanded( + child: TransformerPageView( loop: false, controller: IndexController(), itemBuilder: (BuildContext context, int index) { - return new Container( + return Container( decoration: BoxDecoration( color: colorList[index % colorList.length], border: Border.all(color: Colors.white)), - child: new Center( - child: new Text( + child: Center( + child: Text( "$index", - style: new TextStyle( + style: const TextStyle( fontSize: 80.0, color: Colors.white), ), ), @@ -44,20 +46,20 @@ class ViewPagerDemoPage extends StatelessWidget { }, itemCount: 3), ), - new Expanded( - child: new TransformerPageView( + Expanded( + child: TransformerPageView( loop: true, controller: IndexController(), - transformer: new AccordionTransformer(), + transformer: AccordionTransformer(), itemBuilder: (BuildContext context, int index) { - return new Container( + return Container( decoration: BoxDecoration( color: colorList[index % colorList.length], border: Border.all(color: Colors.white)), - child: new Center( - child: new Text( + child: Center( + child: Text( "$index", - style: new TextStyle( + style: const TextStyle( fontSize: 80.0, color: Colors.white), ), ), @@ -65,20 +67,20 @@ class ViewPagerDemoPage extends StatelessWidget { }, itemCount: 3), ), - new Expanded( - child: new TransformerPageView( + Expanded( + child: TransformerPageView( loop: true, controller: IndexController(), - transformer: new ThreeDTransformer(), + transformer: ThreeDTransformer(), itemBuilder: (BuildContext context, int index) { - return new Container( + return Container( decoration: BoxDecoration( color: colorList[index % colorList.length], border: Border.all(color: Colors.white)), - child: new Center( - child: new Text( + child: Center( + child: Text( "$index", - style: new TextStyle( + style: const TextStyle( fontSize: 80.0, color: Colors.white), ), ), @@ -86,20 +88,20 @@ class ViewPagerDemoPage extends StatelessWidget { }, itemCount: 3), ), - new Expanded( - child: new TransformerPageView( + Expanded( + child: TransformerPageView( loop: true, controller: IndexController(), - transformer: new DeepthPageTransformer(), + transformer: DeepthPageTransformer(), itemBuilder: (BuildContext context, int index) { - return new Container( + return Container( decoration: BoxDecoration( color: colorList[index % colorList.length], border: Border.all(color: Colors.white)), - child: new Center( - child: new Text( + child: Center( + child: Text( "$index", - style: new TextStyle( + style: const TextStyle( fontSize: 80.0, color: Colors.white), ), ), @@ -119,13 +121,13 @@ class AccordionTransformer extends PageTransformer { Widget transform(Widget child, TransformInfo info) { double position = info.position!; if (position < 0.0) { - return new Transform.scale( + return Transform.scale( scale: 1 + position, alignment: Alignment.topRight, child: child, ); } else { - return new Transform.scale( + return Transform.scale( scale: 1 - position, alignment: Alignment.bottomLeft, child: child, @@ -145,10 +147,10 @@ class ThreeDTransformer extends PageTransformer { // left scrolling pivotX = width; } - return new Transform( - transform: new Matrix4.identity() - ..rotate(new vector.Vector3(0.0, 2.0, 0.0), position * 1.5), - origin: new Offset(pivotX!, height / 2), + return Transform( + transform: Matrix4.identity() + ..rotate(vector.Vector3(0.0, 2.0, 0.0), position * 1.5), + origin: Offset(pivotX!, height / 2), child: child, ); } @@ -162,9 +164,9 @@ class ZoomInPageTransformer extends PageTransformer { double position = info.position!; double? width = info.width; if (position > 0 && position <= 1) { - return new Transform.translate( - offset: new Offset(-width! * position, 0.0), - child: new Transform.scale( + return Transform.translate( + offset: Offset(-width! * position, 0.0), + child: Transform.scale( scale: 1 - position, child: child, ), @@ -205,11 +207,11 @@ class ZoomOutPageTransformer extends PageTransformer { double opacity = MIN_ALPHA + (scaleFactor - MIN_SCALE) / (1 - MIN_SCALE) * (1 - MIN_ALPHA); - return new Opacity( + return Opacity( opacity: opacity, - child: new Transform.translate( - offset: new Offset(dx, 0.0), - child: new Transform.scale( + child: Transform.translate( + offset: Offset(dx, 0.0), + child: Transform.scale( scale: scaleFactor, child: child, ), @@ -232,26 +234,26 @@ class DeepthPageTransformer extends PageTransformer { Widget transform(Widget child, TransformInfo info) { double position = info.position!; if (position <= 0) { - return new Opacity( + return Opacity( opacity: 1.0, - child: new Transform.translate( - offset: new Offset(0.0, 0.0), - child: new Transform.scale( + child: Transform.translate( + offset: const Offset(0.0, 0.0), + child: Transform.scale( scale: 1.0, child: child, ), ), ); } else if (position <= 1) { - const double MIN_SCALE = 0.75; + const double minScale = 0.75; // Scale the page down (between MIN_SCALE and 1) - double scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - position); + double scaleFactor = minScale + (1 - minScale) * (1 - position); - return new Opacity( + return Opacity( opacity: 1.0 - position, - child: new Transform.translate( - offset: new Offset(info.width! * -position, 0.0), - child: new Transform.scale( + child: Transform.translate( + offset: Offset(info.width! * -position, 0.0), + child: Transform.scale( scale: scaleFactor, child: child, ), @@ -272,17 +274,17 @@ class ScaleAndFadeTransformer extends PageTransformer { _scale = scale; @override - Widget transform(Widget item, TransformInfo info) { + Widget transform(Widget child, TransformInfo info) { double position = info.position!; double scaleFactor = (1 - position.abs()) * (1 - _scale); double fadeFactor = (1 - position.abs()) * (1 - _fade); double opacity = _fade + fadeFactor; double scale = _scale + scaleFactor; - return new Opacity( + return Opacity( opacity: opacity, - child: new Transform.scale( + child: Transform.scale( scale: scale, - child: item, + child: child, ), ); } diff --git a/lib/widget/vp_list_demo_page.dart b/lib/widget/vp_list_demo_page.dart index b8cf5d1..39d65ee 100644 --- a/lib/widget/vp_list_demo_page.dart +++ b/lib/widget/vp_list_demo_page.dart @@ -6,7 +6,7 @@ import 'package:flutter/rendering.dart'; ///对应文章解析 https://juejin.cn/post/7116267156655833102 ///简单处理处理 pageview 嵌套 listview 的斜滑问题 class VPListView extends StatefulWidget { - const VPListView({Key? key}) : super(key: key); + const VPListView({super.key}); @override State createState() => _VPListViewState(); @@ -17,20 +17,20 @@ class _VPListViewState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("VPListView"), + title: const Text("VPListView"), ), extendBody: true, body: MediaQuery( ///调高 touchSlop 到 50 ,这样 pageview 滑动可能有点点影响, ///但是大概率处理了斜着滑动触发的问题 data: MediaQuery.of(context).copyWith( - gestureSettings: DeviceGestureSettings( + gestureSettings: const DeviceGestureSettings( touchSlop: 50, )), child: PageView( scrollDirection: Axis.horizontal, pageSnapping: true, - children: [ + children: const [ HandlerListView(), HandlerListView(), ], @@ -41,6 +41,8 @@ class _VPListViewState extends State { } class HandlerListView extends StatefulWidget { + const HandlerListView({super.key}); + @override _MyListViewState createState() => _MyListViewState(); } @@ -51,7 +53,7 @@ class _MyListViewState extends State { return MediaQuery( ///这里 touchSlop 需要调回默认 data: MediaQuery.of(context).copyWith( - gestureSettings: DeviceGestureSettings( + gestureSettings: const DeviceGestureSettings( touchSlop: kTouchSlop, )), child: ListView.separated( @@ -74,6 +76,8 @@ class _MyListViewState extends State { ///对应文章解析 https://juejin.cn/post/7116267156655833102 ///垂直滑动的 ViewPage 里嵌套垂直滑动的 ListView class VPNestListView extends StatefulWidget { + const VPNestListView({super.key}); + @override _VPNestListViewState createState() => _VPNestListViewState(); } @@ -104,13 +108,13 @@ class _VPNestListViewState extends State { if (_listScrollController?.hasClients == true && _listScrollController?.position.context.storageContext != null) { ///获取 ListView 的 renderBox - final RenderBox? renderBox = _listScrollController + final RenderBox renderBox = _listScrollController ?.position.context.storageContext .findRenderObject() as RenderBox; ///判断触摸的位置是否在 ListView 内 ///不在范围内一般是因为 ListView 已经滑动上去了,坐标位置和触摸位置不一致 - if (renderBox?.paintBounds + if (renderBox.paintBounds .shift(renderBox.localToGlobal(Offset.zero)) .contains(details.globalPosition) == true) { @@ -169,7 +173,7 @@ class _VPNestListViewState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text("VPNestListView"), + title: const Text("VPNestListView"), ), extendBody: true, body: RawGestureDetector( @@ -208,7 +212,7 @@ class _VPNestListViewState extends State { )), Container( color: Colors.green, - child: Center( + child: const Center( child: Text( 'Page View', style: TextStyle(fontSize: 50), @@ -227,7 +231,7 @@ class KeepAliveListView extends StatefulWidget { final ScrollController? listScrollController; final int itemCount; - KeepAliveListView({ + const KeepAliveListView({super.key, required this.listScrollController, required this.itemCount, }); @@ -262,6 +266,8 @@ class KeepAliveListViewState extends State ///对应文章解析 https://juejin.cn/post/7116267156655833102 ///listView 里嵌套 PageView class ListViewNestVP extends StatefulWidget { + const ListViewNestVP({super.key}); + @override _ListViewNestVPState createState() => _ListViewNestVPState(); } @@ -359,7 +365,7 @@ class _ListViewNestVPState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("ListViewNestVP"), + title: const Text("ListViewNestVP"), ), body: RawGestureDetector( gestures: { @@ -382,12 +388,12 @@ class _ListViewNestVPState extends State { child: ListView.builder( ///屏蔽默认的滑动响应 - physics: NeverScrollableScrollPhysics(), + physics: const NeverScrollableScrollPhysics(), controller: _listScrollController, itemCount: 5, itemBuilder: (context, index) { if (index == 0) { - return Container( + return SizedBox( height: 300, child: KeepAlivePageView( pageController: _pageController, @@ -401,7 +407,7 @@ class _ListViewNestVPState extends State { child: Center( child: Text( "Item $index", - style: TextStyle(fontSize: 40, color: Colors.blue), + style: const TextStyle(fontSize: 40, color: Colors.blue), ), )); }), @@ -415,7 +421,7 @@ class KeepAlivePageView extends StatefulWidget { final PageController pageController; final int itemCount; - KeepAlivePageView({ + const KeepAlivePageView({super.key, required this.pageController, required this.itemCount, }); @@ -438,18 +444,18 @@ class KeepAlivePageViewState extends State ScrollConfiguration.of(context).copyWith(overscroll: false), ///屏蔽默认的滑动响应 - physics: NeverScrollableScrollPhysics(), + physics: const NeverScrollableScrollPhysics(), itemCount: widget.itemCount, itemBuilder: (context, index) { return Container( height: 300, + color: Colors.redAccent, child: Center( child: Text( "$index", - style: TextStyle(fontSize: 40, color: Colors.yellowAccent), + style: const TextStyle(fontSize: 40, color: Colors.yellowAccent), ), ), - color: Colors.redAccent, ); }, ); @@ -461,13 +467,15 @@ class KeepAlivePageViewState extends State ///listView 联动 listView class ListViewLinkListView extends StatefulWidget { + const ListViewLinkListView({super.key}); + @override _ListViewLinkListViewState createState() => _ListViewLinkListViewState(); } class _ListViewLinkListViewState extends State { - ScrollController _primaryScrollController = ScrollController(); - ScrollController _subScrollController = ScrollController(); + final ScrollController _primaryScrollController = ScrollController(); + final ScrollController _subScrollController = ScrollController(); Drag? _primaryDrag; Drag? _subDrag; @@ -524,7 +532,7 @@ class _ListViewLinkListViewState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text("ListViewLinkListView"), + title: const Text("ListViewLinkListView"), ), body: RawGestureDetector( gestures: { @@ -546,11 +554,11 @@ class _ListViewLinkListViewState extends State { ScrollConfiguration.of(context).copyWith(overscroll: false), child: Row( children: [ - new Expanded( + Expanded( child: ListView.builder( ///屏蔽默认的滑动响应 - physics: NeverScrollableScrollPhysics(), + physics: const NeverScrollableScrollPhysics(), controller: _primaryScrollController, itemCount: 55, itemBuilder: (context, index) { @@ -560,19 +568,19 @@ class _ListViewLinkListViewState extends State { child: Center( child: Text( "Item $index", - style: TextStyle( + style: const TextStyle( fontSize: 40, color: Colors.blue), ), )); })), - new SizedBox( + const SizedBox( width: 5, ), - new Expanded( + Expanded( child: ListView.builder( ///屏蔽默认的滑动响应 - physics: NeverScrollableScrollPhysics(), + physics: const NeverScrollableScrollPhysics(), controller: _subScrollController, itemCount: 55, itemBuilder: (context, index) { @@ -583,7 +591,7 @@ class _ListViewLinkListViewState extends State { child: Text( "Item $index", style: - TextStyle(fontSize: 40, color: Colors.white), + const TextStyle(fontSize: 40, color: Colors.white), ), ), ); diff --git a/lib/widget/wrap_content_page.dart b/lib/widget/wrap_content_page.dart index 5ac1ad8..8b2f66c 100644 --- a/lib/widget/wrap_content_page.dart +++ b/lib/widget/wrap_content_page.dart @@ -2,11 +2,13 @@ import 'package:flutter/material.dart'; ///展示如何在 Flutter 里实现 WrapContent 的状态 class WrapContentPage extends StatelessWidget { + const WrapContentPage({super.key}); + @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: new Text( + title: const Text( "WrapContentPage", ), ), @@ -16,14 +18,14 @@ class WrapContentPage extends StatelessWidget { ///关键就是 minHeight 和 double.infinity ///这样就可以由内部 children 来支撑决定外部大小 - BoxConstraints(minHeight: 100, maxHeight: double.infinity), + const BoxConstraints(minHeight: 100, maxHeight: double.infinity), child: Column( ///min而不是max mainAxisSize: MainAxisSize.min, children: [ Container( ///关键就是 minHeight 和 double.infinity - constraints: BoxConstraints( + constraints: const BoxConstraints( minHeight: 100, maxHeight: double.infinity, ), @@ -31,11 +33,11 @@ class WrapContentPage extends StatelessWidget { /// Stack 默认是 StackFit.loose, 需要内部一个固定的最大大小来支撑 child: Stack( children: [ - new Container( + Container( height: 400, color: Colors.yellow, ), - new Container( + Container( height: 50, color: Colors.red, ), @@ -47,7 +49,7 @@ class WrapContentPage extends StatelessWidget { height: 56, alignment: Alignment.centerLeft, color: Colors.blueGrey, - child: new Container( + child: Container( width: 33, height: 33, color: Colors.black, @@ -58,19 +60,19 @@ class WrapContentPage extends StatelessWidget { ), ), Container( - margin: EdgeInsets.only(top: 20), + margin: const EdgeInsets.only(top: 20), ///关键就是 minHeight 和 double.infinity constraints: - BoxConstraints(minHeight: 100, maxHeight: double.infinity), + const BoxConstraints(minHeight: 100, maxHeight: double.infinity), child: Column( mainAxisSize: MainAxisSize.min, children: [ - new Container( + Container( height: 600, color: Colors.green, ), - new Container( + Container( height: 50, color: Colors.amber, ), diff --git a/pubspec.lock b/pubspec.lock index 5d3fbd6..214101d 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -270,6 +270,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "1.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "9e8c3858111da373efc5aa341de011d9bd23e2c5c5e0c62bccf32438e192d7b1" + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.2" flutter_swiper_view: dependency: "direct main" description: @@ -379,6 +387,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "2.0.1" + lints: + dependency: transitive + description: + name: lints + sha256: cbf8d4b858bb0134ef3ef87841abdf8d63bfc255c266b7bf6b39daa1085c4290 + url: "https://pub.flutter-io.cn" + source: hosted + version: "3.0.0" logging: dependency: transitive description: @@ -633,7 +649,7 @@ packages: source: hosted version: "1.3.0" vector_math: - dependency: transitive + dependency: "direct main" description: name: vector_math sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" diff --git a/pubspec.yaml b/pubspec.yaml index c767b63..e615a52 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -132,9 +132,11 @@ dependencies: path: zflutter/ + vector_math: any dev_dependencies: build_runner: ^2.0.5 build_web_compilers: ^3.0.0 + flutter_lints: 3.0.2 flutter_test: sdk: flutter diff --git a/test/widget_test.dart b/test/widget_test.dart index 4c0e043..d486989 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -13,7 +13,7 @@ import 'package:gsy_flutter_demo/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. - await tester.pumpWidget(MyApp()); + await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget);