Skip to content

Instantly share code, notes, and snippets.

View timsneath's full-sized avatar

Tim Sneath timsneath

View GitHub Profile
import 'dart:async';
import 'dart:math' show Random;
main() async {
print('Compute π using the Monte Carlo method.');
await for (final estimate in computePi().take(100)) {
print('π ≅ $estimate');
}
}
/// Generates a stream of increasingly accurate estimates of π.
@timsneath
timsneath / nullsafe.dart
Created October 22, 2020 17:23
nullsafe.dart
// In null-safe Dart, none of these can ever be null.
var widget = Text('Hello');
final status = GetStatus();
String m = '';
void honk(int? loudness) {
if (loudness == null) {
// No loudness specified, notify the developer
// with maximum loudness.
_playSound('error.wav', volume: 11);
return;
}
// Loudness is non-null, let's just clamp it to acceptable levels.
_playSound('honk.wav', volume: loudness.clamp(0, 11));
}
class StatusLine extends StatelessWidget {
final Status status;
StatusLine({this.status: Status.failed});
@override
Widget build(BuildContext context) {
// This local variable is non-nullable, but not initialized.
String statusText;
if (status == Status.ok) {
statusText = 'Update succeeded';
} else {
// These are all nullable variables.
Text? t = Text('Hello'); // Can be null later.
final Status? s = getStatus(); // Maybe the function returns null.
String? n; // Is null at first. Can be null at any later time, too.
// In function parameters.
void initialize(int? count) {
// It's possible that count is null.
}
// In function return values.
static List<double?>? getTemperatures() {
// Can return null instead of a List, and the list can contain nulls.
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Get data from services. Note: in a real application,
// these would be async calls, but we're using sync calls
// for simplicity.
final localizedAppName = Config.getAppName();
final temperatures = WeatherService.getTemperatures();
return MaterialApp(
home: Scaffold(
@timsneath
timsneath / filepicker.dart
Last active September 22, 2020 05:17
filepicker.dart
import 'package:filepicker_windows/filepicker_windows.dart';
void main() {
final file = OpenFilePicker()
..filterSpecification = {
'Word Document (*.doc)': '*.doc',
'Web Page (*.htm; *.html)': '*.htm;*.html',
'Text Document (*.txt)': '*.txt',
'All Files': '*.*'
}
@timsneath
timsneath / IFileDialog.dart
Created September 22, 2020 05:10
IFileDialog.dart (extract)
import 'dart:ffi';
import 'package:ffi/ffi.dart';
// more imports
import 'IModalWindow.dart';
/// @nodoc
const IID_IFileDialog = '{42f85136-db7e-439c-85f1-e4075d135fc8}';
@timsneath
timsneath / IFileDialog.h
Created September 22, 2020 05:07
IFileDialog.h (extract)
#include "windows.h"
#include "Shobjidl.h"
// vtable_start 4
MIDL_INTERFACE("42f85136-db7e-439c-85f1-e4075d135fc8")
IFileDialog : public IModalWindow
{
public:
virtual HRESULT STDMETHODCALLTYPE SetFileTypes(
/* [in] */ UINT cFileTypes,