How to Use Functions of Another File In Dart / Flutter?

3 min read
How to Use Functions of Another File In Dart Flutter
How to Use Functions of Another File In Dart Flutter

ListView Widget is one of the important widget types that can be used anywhere. So in this article today, we will take a deep dive into learning how to use Functions of Another File In Dart / Flutter.

Are you ready for the same?

How to Use Functions of Another File In Dart / Flutter?

You can write a file with just that function, like:

test.dart will look like a below:

void launchWebView () {
  print("1234");
}

and then import that file like this, main.dart will have a code snippet like the below:

import "test.dart";

class _MyHomePageState extends State<MyHomePage> {
   @override
   Widget build(BuildContext context) {
       launchWebView();

It is not really clean, but you can do that. Alternatively, you can use a class with a static method as shown in the below snippet:

class test {
    static void foo() {
        print("1234");
    }
}

and then in your code invoke it like that (after the import):

test.foo();

Or you can just declare all your functions (helpers) inside a class and pass them as an argument to other classes.

//The class which contains your functions
class HelperFunction{

  //Define your method
  void launchWebView () {
    print("1234");
  }

  //Pass that function to a class
  MyHomePage(launchWebView);

}

//The class which receives the function.
class MyHomePage extends StatefulWidget{
  //Retrieve the function and store it to a variable of type Function.
  final Function launchWebView;
  MyHomePage(this.launchWebView);
}

class _MyHomePageState extends State<MyHomePage> {
   @override
   Widget build(BuildContext context) {
     //Access that function in State class using widget keyword.
     widget.launchWebView();
   }
}

Conclusion:

Thanks for being with us on a聽Flutter Journey聽!!! Lots of amazing content coming up your way!! Stay Tuned!!

Tell us what methods you have used in the past for these problems!!

So in this article, we have been through how to use Functions of Another File In Dart / Flutter.

Also, If you still have doubts about Flutter Development !!! Just let us know, We would love to assist you聽馃檪

Keep聽Learning聽!!! Keep聽Fluttering聽!!! Stay Connected !!!

Don鈥檛 forget to leave your valuable feedback in the comments!!! It keeps the enthusiasm going聽馃檪

Flutter Agency聽is our portal Platform dedicated to聽Flutter聽Technology and聽Flutter Developers. The portal is full of cool resources from聽Flutter聽like聽Flutter Widget聽Guide,聽Flutter Projects,聽Code libs聽and etc.

Flutter Agency聽is one of the most popular online portal dedicated to聽Flutter Technology聽and daily thousands of unique visitors come to this portal to enhance their knowledge of聽Flutter

Leave a Reply