Open In App

How to use Functions of Another File in Flutter?

Improve
Improve
Like Article
Like
Save
Share
Report

Flutter is an open-source framework by Google for building beautiful, natively compiled, multi-platform applications from a single codebase. A Single codebase means that only we have to write a single code for Android and IOS and others like Desktop  Application, Web Application.

So, Today we are going to learn How to use the Function of another file in Dart or Flutter.

There are a couple of different methods for implementing the Function of another file in dart or flutter and some are Global function, static method, mixin, etc.

Method 1: Global function 

Using global functions doesn’t follow Object Oriented programming concept. Global state breaks the Encapsulation principle. OOP is the best basic paradigm to use within Dart apps because of the way the language is designed (classes).

Define a function in a file,  just say global.dart.

Dart




void func() 
{
  print('Hello GEEKS FOR GEEKS');
}


To use it in any file, just call:

Dart




import 'package:sample/global.dart';
  
main() {
  func();
}


Note: Don’t forget to import the global.dart file.

Method 2: Static function in a Class

Static functions break the encapsulation property of OOP and the Open-Closed principle. They are hard to integrate with state management solutions because we track the state within instance method contexts. For example, integrating providers and other packages like GetX.

Create a class, say Sample in file global.dart , and define your function func in it:

Dart




class Sample {
  static void func() => print('Hello Geeks for Geeks');
}


To use it in any file, just call:

Dart




Sample.func();


Note: Don’t forget to import the global.dart file.

Method 3: Mixins

Dart has inbuilt support for optionally adding functions to a class when we want to reduce duplicated code but avoid extending the whole class (Source). The mixin keyword enables this by mixing a class with some specific logic. We can restrict the mixin to a specific subclass with on if needed.

Create a mixin, say web:

Dart




mixin Web {
  void func() => print('Hello');
}


To use it in a class, just use with a keyword followed by the mixin.

Dart




class Site with Web {
  void main() => func();
}


These are a couple of ways you can use a function from another file in Dart/Flutter.



Last Updated : 09 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads