How to stop(or pause or cancel or dispose) Stream.periodic() in Flutter (UI)

Viewed 206

I am creating a counter using Stream.periodic(), I want Stream.periodic() to stop when it counts to 0.

Here is my source code

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage1(),
    );
  }
}

class MyHomePage1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("APP DEMO"),
      ),
      body: Center(
        child: StreamBuilder(
            stream: stream(20),
            builder: (context, AsyncSnapshot<int> snapshot) {
              if (snapshot.error != null) {
                debugPrint("error code ");
                  /* I want to stop (or cancel) _stream here */
              }

              return Text('Timer: ${snapshot.data}',
                  style: TextStyle(fontSize: 20));
            }),
      ),
    );
  }

  Stream<int> stream(int val) {   
    Stream<int> _stream = Stream.periodic(Duration(seconds: 1), (int i) {
      int ret = val - i;
      if (ret == 0) {
        throw ("error ");
        /*Or, I want to stop (or cancel) _stream here */
      }
      return val - i;
    });
    return _stream;
  }
}
  1. How can I stop Stream.periodic() in StreamBuilder?
  2. It seems to have to destroy the listener in StreamBuilder right? If yes please show me how to do it!
0 Answers
Related