簡體   English   中英

如何在 flutter 中顯示“for”循環進度指示器

[英]how to show 'for' loop progress Indicator in flutter

我有一個打印“hello world”100 次的循環。 所以我想要的是顯示進度指示器,它顯示循環進度..例如:如果循環打印總計 100 次中的 50 次,則進度指示器應為 50%..

就像評論中提到的 @pskink 一樣, LinearProgressIndicatorCircularProgressIndicator應該可以解決問題。 做 go 更詳細一點,你可以在每次迭代后存儲進度(或者根據你的需要每隔這么多次迭代),如果你使用你的小部件的 state ,重建應該自動觸發並重建進度指示器每次都有新的價值。 這看起來有點像:

// inside the State
double progress = 0.0;

doTheLoop() {
  for (int i = 0; i < 100; i++) {
    print('Hello world');
    setState(() => progress = i/100);
  }
}

build(BuildContext context) {
  return Column(children: [
    Container(
      // the progress indicator updates when the progress variable in the state updates, since a rebuild is triggered
      child: LinearProgressIndicator(
        progress: progress,
      );
    ),
    
    // press the button to start the loop
    ElevatedButton(
      child: Text('Start loop'),
      onPressed: doTheLoop,
    ),
  ],),
}

這里 Direct Setstate不起作用,因為 for 循環會盡快執行。所以我們為視覺進度添加 100 毫秒的時間延遲

await Future.delayed(Duration(milliseconds: 100));

線性微件

LinearProgressIndicator(
                minHeight: 25,
                value: _value,
                color: _color,
                semanticsValue: (_value * 100).toString(),
                semanticsLabel: (_value * 100).toString(),
              )

同時按下循環按鈕

  Future<void> loop() async {
    for (int i = 0; i <= 100; i++) {

      await Future.delayed(Duration(milliseconds: 100));
      var element = i;
      print(element);
      setState(() {
        _value = element / 100;
        print(_value);
      });
      if (element < 5 && element > 0)
        _color = Colors.red;
      else if (element < 25 && element > 5)
        _color = Colors.cyan;
      else if (element < 50 && element > 25)
        _color = Colors.lightGreenAccent;
      else if (element < 75 && element > 50)
        _color = Colors.lightGreen;
      else if (element < 100 && element > 75) _color = Colors.green;
    }
  }

在此處輸入圖像描述

沒有 Streamcontroller飛鏢板

import 'dart:async';

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 MaterialApp(
      initialRoute: "/",
      routes: {
        "/": (context) => Home(),
      },
      title: _title,
      // home: ,
    );
  }
}

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("title")),
      body: const Center(
        child: MyStatelessWidget(),
      ),
    );
  }
}

var _color = Colors.black;
var _value = 0.0;

class MyStatelessWidget extends StatefulWidget {
  const MyStatelessWidget({Key? key}) : super(key: key);

  @override
  State<MyStatelessWidget> createState() => _MyStatelessWidgetState();
}

class _MyStatelessWidgetState extends State<MyStatelessWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(8),
            child: Stack(
              children: [
                Positioned(
                  child: Container(
                    height: 100,
                    width: 100,
                    child: CircularProgressIndicator(
                      strokeWidth: 4,
                      value: _value,
                      color: _color,
                    ),
                  ),
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                ),
                Positioned(
                  child: Text(
                    (_value * 100).toStringAsFixed(1),
                    style: TextStyle(fontSize: 15),
                  ),
                  top: 25,
                  left: 10,
                ),
              ],
            ),
            height: 75,
            width: 75,
          ),
          Container(
              padding: EdgeInsets.all(8),
              child: LinearProgressIndicator(
                minHeight: 25,
                value: _value,
                color: _color,
                semanticsValue: (_value * 100).toString(),
                semanticsLabel: (_value * 100).toString(),
              )),
          Text(
            (_value * 100).toStringAsFixed(1),
            style: TextStyle(fontSize: 25),
          ),
          Row(
            children: [
              Expanded(
                child: IconButton(
                  onPressed: () {
                    loop();
                  },
                  icon: Icon(
                    Icons.not_started_outlined,
                    size: 45,
                  ),
                ),
              ),
              Expanded(
                child: IconButton(
                  onPressed: () {},
                  icon: Icon(Icons.stop, size: 45),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Future<void> loop() async {
    for (int i = 0; i <= 100; i++) {
      // if (!stream.isClosed) stream.sink.addStream(Stream.value(i));
      await Future.delayed(Duration(milliseconds: 100));
      var element = i;
      print(element);
      setState(() {
        _value = element / 100;
        print(_value);
      });
      if (element < 5 && element > 0)
        _color = Colors.red;
      else if (element < 25 && element > 5)
        _color = Colors.cyan;
      else if (element < 50 && element > 25)
        _color = Colors.lightGreenAccent;
      else if (element < 75 && element > 50)
        _color = Colors.lightGreen;
      else if (element < 100 && element > 75) _color = Colors.green;
    }
  }

  @override
  void initState() {}
}

此 Sample.Here 使用streamcontroller .so 使用 stream controller 管理暫停或停止進度等進度。

SampleCode Dart pad活碼

import 'dart:async';

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 MaterialApp(
      initialRoute: "/",
      routes: {
        "/": (context) => Home(),
      },
      title: _title,
      // home: ,
    );
  }
}

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("title")),
      body: const Center(
        child: MyStatelessWidget(),
      ),
    );
  }
}

var _color = Colors.black;
var _value = 0.0;

class MyStatelessWidget extends StatefulWidget {
  const MyStatelessWidget({Key? key}) : super(key: key);

  @override
  State<MyStatelessWidget> createState() => _MyStatelessWidgetState();
}

class _MyStatelessWidgetState extends State<MyStatelessWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.all(8),
            child: Stack(
              children: [
                Positioned(
                  child: Container(
                    height: 100,
                    width: 100,
                    child: CircularProgressIndicator(
                      strokeWidth: 4,
                      value: _value,
                      color: _color,
                    ),
                  ),
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                ),
                Positioned(
                  child: Text(
                    (_value * 100).toStringAsFixed(1),
                    style: TextStyle(fontSize: 15),
                  ),
                  top: 25,
                  left: 10,
                ),
              ],
            ),
            height: 75,
            width: 75,
          ),
          Container(
              padding: EdgeInsets.all(8),
              child: LinearProgressIndicator(
                minHeight: 25,
                value: _value,
                color: _color,
                semanticsValue: (_value * 100).toString(),
                semanticsLabel: (_value * 100).toString(),
              )),
          Text(
            (_value * 100).toStringAsFixed(1),
            style: TextStyle(fontSize: 25),
          ),
          Row(
            children: [
              Expanded(
                child: IconButton(
                  onPressed: () {
                    loop();
                  },
                  icon: Icon(
                    Icons.not_started_outlined,
                    size: 45,
                  ),
                ),
              ),
              Expanded(
                child: IconButton(
                  onPressed: () {
                    stream.close();
                  },
                  icon: Icon(Icons.stop, size: 45),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Future<void> loop() async {
    for (int i = 0; i <= 100; i++) {
      if (!stream.isClosed) stream.sink.addStream(Stream.value(i));
      await Future.delayed(Duration(milliseconds: 100));
    }
    // List.generate(100, (index) => index + 1).forEach((element) async {
    //   if (!stream.isClosed) stream.sink.addStream(Stream.value(element));
    //   await Future.delayed(Duration(seconds: 1));
    // });
  }

  // late StreamController<int> stream;
  StreamController<int> stream = StreamController();

  @override
  void initState() {
    stream.stream.listen((element) {
      print(element);
      setState(() {
        _value = element / 100;
        print(_value);
      });
      if (element < 5 && element > 0)
        _color = Colors.red;
      else if (element < 25 && element > 5)
        _color = Colors.cyan;
      else if (element < 50 && element > 25)
        _color = Colors.lightGreenAccent;
      else if (element < 75 && element > 50)
        _color = Colors.lightGreen;
      else if (element < 100 && element > 75) _color = Colors.green;
    });
  }
}

請試試這個

 class testwidget extends StatefulWidget {
  const testwidget({Key? key}) : super(key: key);

  @override
  _test createState() => _test();
}

class _test extends State<testwidget> {

  StreamController loopValueStram=new StreamController();
  var loopProgress=0.0;
  static const  max=100;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loopValueStram.stream.listen((event) {
      setState(() {
        loopProgress=event;
      });
    });
  }

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



  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('test'),
        ),
        body: Center(
          child:Column(
            children: [
              RaisedButton(
                onPressed: (){
                  loop();
                },
                child: Text("Start loop ${(loopProgress*100).toInt()}%"),
              ),
              SizedBox(height: 10,),
              Padding(padding: EdgeInsets.all(20),
                child: Visibility(
                    visible:loopProgress>0,
                    child: LinearProgressIndicator(
                      value: loopProgress.toDouble(),
                      semanticsLabel: "Progress",
                      minHeight: 40,
                    )),
              )
            ],
          )
        )
    );
  }

  Future<void> loop() async {
    for(int i=0;i<=100;i++){
      loopValueStram.sink.add(i/100);
      await Future.delayed(Duration(seconds: 1));// this line is to slowdown itération so we can see linear pregression well
    }
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM