Programming Flutter

Updates

Constructor Syntax

Book gives:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

Errors:

  • “The parameter ‘key’ can’t have a value of ‘null’ because of its type, but the implicit default value is ‘null’. Try adding either an explicit non-‘null’ default value or the ‘required’”
    • Change Key to optional: Key?
    • Add required before this.title

Integration Testing

Dart null safety means you have to use generated code for mocking now.

import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:xckd_app/main.dart';
import 'dart:io';

@GenerateNiceMocks([MockSpec<http.Client>(), MockSpec<File>()])
import 'unit_test.mocks.dart';

const comics = [/* ... */];

void main() {
  test("get latest comic number", () async {
    var latestComicNumberFile = MockFile();
    var latestComicNumberExists = false;

    when(mockHttp.read(Uri.parse('https://xkcd.com/info.0.json')))
        .thenAnswer((_) {
      return Future.value(comics[1]);
    });

    expect(
      await getLatestComicNumber(
        httpClient: mockHttp,
        latestComicNFile: latestComicNumberFile,
      ),
      2,
    );
  });
}