dartasynchronousplaygroundsdartpad

How to STOP a program in DartPad?


Using DartPad, how do you stop the current program without losing all your code?

As it is, it seems there is only:

The answer is not:

(because evidently it doesn't stop the current code first, and in fact begins subsequent runs in parallel! ***)

(because what if you're needing to read rapidly changing console output? -- that would be gone)

*** You can verify this behavior with this code:

import 'dart:async';

void main() {
  
  int iter = 0;
  
  Timer myTimer = Timer.periodic(Duration(milliseconds: 10), (timer) {
    iter++;
   
    int temp = iter %1000;
    
    print("iter = $iter");
    print("iter %1000 = $temp");
  });

}

Solution

  • Since DartPad can run Flutter apps, you can make your own Stop button.

    enter image description here

    Run code sample in DartPad.

    import 'package:flutter/material.dart';
    import 'dart:async';
    
    void main() {
      runApp(MyApp());
      runDart();
    }
    
    Timer? myTimer;
    
    void runDart() {
      int iter = 0;
      myTimer = Timer.periodic(const Duration(milliseconds: 10), (timer) {
        iter++;
        int temp = iter %1000;
        print("iter = $iter");
        print("iter %1000 = $temp");
      });
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Center(
            child: ElevatedButton(
              child: const Text('Stop'),
              onPressed: () {
                myTimer?.cancel();
              },
            ),
          ),
        );
      }
    }