Flutter实现quiz应用60秒进度条报Cannot lerp between "0" and "1"错误如何解决
报错原因
你在QuestionController中初始化Tween时传入的begin: 0、end: 1为int类型,默认Tween类无法直接对int值做插值计算,插值过程生成的double值和int类型不匹配,触发该异常。
修复方法
分两步修改代码即可实现需求:
- 第一步:修改
QuestionController的动画相关代码,明确指定Tween的类型为double:
import 'package:flutter/animation.dart'; import 'package:get/get.dart'; class QuestionController extends GetxController with SingleGetTickerProviderMixin { late AnimationController _animationController; // 明确动画值类型为double late Animation<double> _animation; Animation<double> get animation => _animation; @override void onInit() { _animationController = AnimationController( duration: const Duration(seconds: 60), vsync: this ); // 改用Tween<double>,传入double类型的起止值 _animation = Tween<double>(begin: 0.0, end: 1.0).animate(_animationController) ..addListener(() { update(); }); _animationController.forward(); super.onInit(); } }
- 第二步:修改
ProgressBar组件,将动画值绑定到进度条宽度和倒计时文本上:
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:quizz_app/constants.dart'; import 'package:quizz_app/controllers/question_controllers.dart'; class ProgressBar extends StatelessWidget { const ProgressBar({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Container( width: double.infinity, height: 35, decoration: BoxDecoration( border: Border.all(color: Colors.white.withOpacity(0.2), width: 3), borderRadius: BorderRadius.circular(50) ), child: GetBuilder<QuestionController>( init: QuestionController(), builder: (controller) { return Stack( children: [ LayoutBuilder( builder: (context, constraints) => Container( // 绑定动画值控制进度条宽度 width: constraints.maxWidth * controller.animation.value, decoration: BoxDecoration( gradient: kPrimaryGradient, borderRadius: BorderRadius.circular(50) ), ) ), Positioned.fill( child: Padding( padding: const EdgeInsets.symmetric(horizontal: kDefaultPadding), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text("Time left:", style: TextStyle(fontSize: 20)), // 动态计算剩余秒数 Text( (60 * (1 - controller.animation.value)).round().toString(), style: const TextStyle(fontSize: 20), ), ], ), ) ) ], ); }, ), ); } }
内容的提问来源于stack exchange,提问作者Philippe Tankoano
相关产品推荐
相关产品推荐

