源码
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
/// AnimationControllers can be created with `vsync: this` because of TickerProviderStateMixin.
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
double _counter = 0.0;
int percent = 0;
Future<void> _futureWork() {
return Future.delayed(const Duration(seconds: 1), () =>
setState(() {
_counter = _counter + 0.1;
})
);
}
@override
Widget build(BuildContext context) {
if (_counter < 0.95) {
_futureWork();
}
percent = (_counter * 100.0).round();
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(
'$percent%',
style: const TextStyle(fontSize: 20),
),
LinearProgressIndicator(
value: _counter,
semanticsLabel: 'Linear progress indicator',
),
CircularProgressIndicator(
value: _counter,
semanticsLabel: 'Circular progress indicator',
),
],
),
),
);
}
}
效果
解说
原文用了一个动画来刷新,比较复杂。笔者改了一下,用了老套路,相对简单。这里记录一个浮点转定点的用法。
percent = (_counter * 100.0).round();