Home > Software design >  How to call multiple widgets in dart files on another dart file in flutter?
How to call multiple widgets in dart files on another dart file in flutter?

Time:09-29

I created some dart files from AdobeXD (applebutton.dart, background.dart, googlebutton.dart). However, I don't know how to call these files from the main.dart file.

enter image description here

I can copy and paste part of these AbodeXD generated files into the main.dart file, but I believe there must be a way to call these files without making main.dart bigger.

Inside class MyApp> Widget> body> children, I pasted the Container from background.dart, but I want to call the Widget instead of copying it.

(I am new in flutter so thanks for your answer).

CodePudding user response:

When using items from a different file, you must first import them using the import keyword, like so:

import 'Widgets/my_widget.dart';

another way to import is by calling the full path of the widget:

import 'package:my_project/widgets/my_widget.dart';

most IDEs will give you an option to auto import whatever files you use

enter image description here

CodePudding user response:

A simple solution will be creating another widget just for export and importing just one file.

In this image, I just need to import widgets.dart. The rest of the file will be imported there.

widgets.dart

export 'widget.circleNeonBorder.dart';
export 'widget.rectNeonBorder.dart';
export 'widget.desktopWrapper.dart';
export 'widget.tabletWrapper.dart';
export 'widget.mobileWrapper.dart';

There is Dart Barrel File Generator extension for Vs-code user. You may also find for android-studio.

enter image description here

CodePudding user response:

These all pages have main function. It's not understandable for Dart. Dart files search main function to start, this is why you must use just one main function into your main.dart file.

To use your other screens in the main.dart file, use import keyword on the top of your main.dart files and write the page's path.

The screens must extends with StatelessWidget or StatefulWidget. You're not compile your entire application when you want to show another page, so you dont need to use main() function in each page.

  • Related