5

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

As it is, it seems there is only:

  • a RUN button
  • a RESET button (which wipes your code)

The answer is not:

  • "just leave it running and click RUN again,"

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

  • "just reload the browser tab"

(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");
  });

}
Nerdy Bunz
  • 6,040
  • 10
  • 41
  • 100

2 Answers2

3

There is not a way to stop a program in DartPad yet. Here are some related issues on GitHub:

https://github.com/dart-lang/dart-pad/issues/668

https://github.com/dart-lang/dart-pad/issues/704

Akif
  • 7,098
  • 7
  • 27
  • 53
2

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();
          },
        ),
      ),
    );
  }
}
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • is there a command like exit() or finish() that would actually end the execution entirely? – Nerdy Bunz Dec 20 '21 at 19:21
  • @NerdyBunz I'm not sure. – Suragch Dec 20 '21 at 23:49
  • 1
    @NerdyBunz Yes there is an [`exit()`](https://api.dart.dev/stable/2.15.1/dart-io/exit.html) command, but it requires importing the `dart:io` package which is not supported in the dartpad. Yet. If you'd like to know more, then check the description for the [`exit()`](https://api.dart.dev/stable/2.15.1/dart-io/exit.html) – Harshvardhan Joshi Dec 21 '21 at 08:57