To call a void function from another file in Flutter, there are 2 points you need to know:
- DO NOT name the function with the underscore symbol ( _ ) at the beginning. For instance, _myFunction() cannot be called in another file.
- Import the file that contains the function.
Example
Create a file called test.dart in the lib folder in your Flutter project:
void doSomething(){
print('Hello man');
}
Call the doSomething function in main.dart:
// import test.dart
import './test.dart';
// Other code
// Use the doSomething function
TextButton(child: const Text('Button'), onPressed: doSomething,)
Hope this helps!
Further reading:
- Set Default Parameter Values for a Function in Flutter
- Flutter: Import only 1 class from a file contains multi classes
- Best Libraries for Making HTTP Requests in Flutter
- Flutter: Caching Network Images for Big Performance gains
- How to embed Youtube video in Flutter
You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.