Complete Flutter Project Solutions

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’t 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 GuideFlutter ProjectsCode 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

Request a Quote