Flutter 进度条 LinearProgressIndicator

121 阅读1分钟

进度条

class ProgressHandle extends StatefulWidget {
  const ProgressHandle({super.key});

  @override
  State<ProgressHandle> createState() => _ProgressHandleState();
}

class _ProgressHandleState extends State<ProgressHandle> {
  StreamController<double> controller = StreamController();

  int count = 0;

  @override
  void initState() {
    super.initState();
    Timer.periodic(
      Duration(milliseconds: 100),
      (Timer t) {
        count++;
        controller.add(1.0 * count);
        if (count >= 100) {
          t.cancel();
        }
      },
    );
  }

  @override
  void dispose() {
    controller.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<double>(
        stream: controller.stream,
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Stack(
                children: [
                  Container(
                    width: 200,
                    height: 200,
                    color: Colors.grey.withOpacity(0.3),
                  ),
                  Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      child: Text(snapshot.data.toString())),
                  Positioned(
                    bottom: 0,
                    right: 0,
                    top: 0,
                    left: 0,
                    child: Container(
                      alignment: Alignment.center,
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 5.0),
                        width: double.infinity,
                        child: snapshot.hasData
                            ? ClipRRect(
                                borderRadius: BorderRadius.circular(20.0),
                                child: LinearProgressIndicator(
                                  minHeight: 20.0,
                                  value: (snapshot.data / 100).toDouble(),
                                  backgroundColor:
                                      const Color.fromRGBO(255, 0, 0, 0.5),
                                  color: Colors.green,
                                  valueColor: AlwaysStoppedAnimation<Color>(
                                      Theme.of(context).primaryColor),
                                ),
                              )
                            : Container(),
                      ),
                    ),
                  ),
                ],
              )
            ],
          );
        });
  }
}```