What’s a good recipe for overriding hashcode in Dart?

The quiver package provides helper functions hash2, hash3, etc., which simplify the task of implementing hashCode, with some assurance that it works properly under the Dart VM and when compiled to JavaScript. import ‘package:quiver/core.dart’; class Person { String name; int age; Person(this.name, this.age); bool operator ==(o) => o is Person && name == o.name && … Read more

How to flatten a List?

The easiest way I know of is to use Iterable.expand() with an identity function. expand() takes each element of an Iterable, performs a function on it that returns an iterable (the “expand” part), and then concatenates the results. In other languages it may be known as flatMap. So by using an identity function, expand will … Read more

How to set state from another widget?

Avoid this whenever possible. It makes these widgets depends on each others and can make things harder to maintain in the long term. What you can do instead, is having both widgets share a common Listenable or something similar such as a Stream. Then widgets interact with each other by submitting events. For easier writing, … Read more

How to customize a date picker

Flutter 2.0.2 showDatePicker( builder: (context, child) { return Theme( data: Theme.of(context).copyWith( colorScheme: ColorScheme.light( primary: Colors.yellow, // header background color onPrimary: Colors.black, // header text color onSurface: Colors.green, // body text color ), textButtonTheme: TextButtonThemeData( style: TextButton.styleFrom( foregroundColor: Colors.red, // button text color ), ), ), child: child!, ); }, ); }, );

How to convert a List to List in null safe Dart?

Ideally you’d start with a List<String> in the first place. If you’re building your list like: String? s = maybeNullString(); var list = <String?>[ ‘foo’, ‘bar’, someCondition ? ‘baz’ : null, s, ]; then you instead can use collection-if to avoid inserting null elements: String? s = maybeNullString(); var list = <String?>[ ‘foo’, ‘bar’, if … Read more

Non-nullable instance field must be initialized

(Your code was fine before Dart 2.12, null safety) With null safety, Dart doesn’t know if you actually assigned a value to count. Dart initializes objects in two phases, and Dart expects all member variables to already be initialized when the constructor’s body executes. Because your members are non-nullable and haven’t been initialized to non-null … Read more