Home > Enterprise >  How to use Logger in your flutter project
How to use Logger in your flutter project

Time:03-08

I want to use logger package provided by dart in my build method Implementation of logger I create a file at the top of the tree called constants.dart constants.dart

    import 'package:logger/logger.dart';


var logger = Logger(
    printer: PrettyPrinter(
  methodCount: 0,
  errorMethodCount: 5,
  lineLength: 50,
  colors: true,
  printEmojis: true,
  printTime: true,
));

I Just import this file then I can use it PROBLEM

  • I am only able to use logger.d(_imageUrl); in the state class not in my build method

ERROR WHEN USING IN BUILD

    @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Edit Products'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(17.0),
        child: Form(
          key: _saveFormKey,
          child: SingleChildScrollView(
            child: Column(
              children: [
                TextFormField(
                  initialValue: _initValues['title'],
                  logger.d('_imageUrl');
                  decoration: const InputDecoration(labelText: 'Title'),
                  textInputAction: TextInputAction.next,
                  validator: (value) {

This is how I use it in the build Inside TEXTFORMFIELD

ERROR MESSAGE

Too many positional arguments: 0 expected, but 1 found. Try removing the extra positional arguments, or specifying the name for named arguments.

Positional arguments must occur before named arguments. Try moving all of the positional arguments before the named arguments.

CodePudding user response:

You can't put a random function in the middle of the constructor of a TextFormField, or any constructor that doesn't take a Function as a parameter (like an onPressed for example).

 TextButton(
      child: Text('Button'),
      onPressed: () {
        logger.d('_imageUrl'); // this would be valid
      },
    )

If you want that in your build method just put it right above your return statement.

  @override
  Widget build(BuildContext context) {
  logger.d('_imageUrl');

    return Scaffold(
      appBar: AppBar(
        title: const Text('Edit Products'),
      ),
...

Edit

I forgot that TextFormField has a few functions in the constructor. So you could also do something like this.

TextFormField(
      onTap: () => logger.d('_imageUrl'),
      onChanged: (text) => logger.d(text),
    )

CodePudding user response:

@Loren.A already describe the situation with solutions. If you like to get immediate value/perform operation before widget, you can use inline function in this case.

(){ 
/// do some stuff, but don't make it heavy operation
return MyWidget(..);
}(),

In your case

() {
  logger.d('_imageUrl');
  return TextFormField(...);
}(),
  • Related