Skip to content

Flutter's WidgetsFlutterBinding.ensureInitialized() and withClock() - causes clock.now() to misbehave #702

@mpszczolinski

Description

@mpszczolinski

If flutter app starts with:

void main() {
  WidgetsFlutterBinding.ensureInitialized();

Then clock.now() prints not mocked value if outside of build method.

Minimum reproduceable code:

import 'package:clock/clock.dart';
import 'package:flutter/material.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  
  withClock(Clock.fixed(DateTime(1990)), () {
    runApp(const MyApp());
  });
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  void _printClockNow() {
    print('_printClockNow is: ${clock.now()}'); // prints real NOW
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    print('build clock.now() is: ${clock.now()}'); // prints mocked NOW

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[Dummy()],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _printClockNow,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

class Dummy extends StatelessWidget {
  @override
  Widget build(Object context) {
    return Text('t: ${clock.now()}');
  }
}

Expected behavior:
clock.now() to have mocked value despite WidgetsFlutterBinding.ensureInitialized()

EDIT:
Changed because I discovered that culprit is WidgetsFlutterBinding.ensureInitialized().

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions