Search code examples
flutterclassdartprovider

how to call a function on class init


I would like to call a function when initializing a provider.

import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:myproj/models/sk_userprofile.dart';

class SkUserProfileProv with ChangeNotifier {
  SkUserProfile? skUser;

  SkUserProfileProv({required this.skUser}) {
    log('hello World');
  }

}

Unfortunately 'hello world' isn't logged. Why doesn't this work?


Solution

  • dart:developer logging only works when Debugging, not when "Running." We can only receive these logs when connected to the VM Service.

    Run your app in debug mode, and it will print, or if it's Dart code only, you can pass --enable-asserts

    If you change this to print, it will show your log in all modes:

    class SkUserProfileProv with ChangeNotifier {
      SkUserProfile? skUser;
    
      SkUserProfileProv({required this.skUser}) {
        print('hello World'); // all modes
        log('hello World'); // only debug mode
      }
    }