'Flutter, create object and call func vs call func with file directly

I'm always confused about creating some reusable business logic function.

Create a class along with file

import 'function_file';

ClassWithFunction cwf = new ClassWithFunction(); 
cwf.function(args); 

Whether to implement it this way, if not, create a function without a class name and

 import 'function_file'; 

 function(args); 

I am always confused about whether to

Which should be answer?



Solution 1:[1]

The class keeps all component data, it's easier to understand and read code. If you have some single helper function, you can create it global outside the class, its no problem with global values in the Dart language everything is global even the class is a global variable. Example:

void main() {
  final car = Car();
  final tractor = Tractor();
  
  car.start(); // The car started
  car.stop(); // The car stopped
  
  tractor.start(); // The tractor started
  tractor.stop(); // The tractor stopped
  
  globalFunction('Print me'); // Print me
}

abstract class Vehicle {
  void start();
  void stop();
}

class Tractor extends Vehicle {
  @override
  void start() {
    print('The tractor started');
  }
  
  @override
  void stop() {
    print('The tractor stopped');
  }
}

class Car extends Vehicle {
   @override
  void start() {
    print('The car started');
  }
  
  @override
  void stop() {
    print('The car stopped');
  }
}

void globalFunction(String data){
  print(data);
} 

Note: Too many global variables can provide to complicate code tests.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1