Skip to content

[Flutter] How to import in Flutter

No matter which applications we are developing, it is difficult for us to put all of programs in one main file (we skip to talk about shortcomings).

Therefore, it is necessary to separate the files of the code according the different functions or widgets, if we need these functions, we can import these functions or widgets.

If you are interested in learning Flutter, you can refer to the official Tutorial: https://flutter.dev/docs/reference/tutorials

If you want to configure your development environment, you can refer: How to install Intellij IDEA

The following simple example how to import.


Import your program

In the default projects folder, the program files developed by Dart is placed under the lib folder. Suppose I have two files:

  • page_01.dart
  • paget_02.dart

Then I want to import the page_02.dart in page_01.dart, the two program files are as follows:

page_02.dart:

import 'package:flutter/material.dart';
class page02 extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.red,
    );
  }
}



Here I have defined the Class page02, which will draw the Container's graphics on the phone screen. For the convenience of display, I set the Container to red.


page_01.dart:

import 'package:flutter/material.dart';
import 'package:new_test/page_02.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: page02(),
      ),
    );
  }
}



Output:

As you can see that the package I imported at the top even contains page_02.dart. In this way, we can set page02() in the body of the program entry point, which is defined in another file and contains the red Container interface.

Tags:

Leave a ReplyCancel reply

Exit mobile version