Segmenting the elements of homepage in multiple >dart files

Viewed 152

Being new to Flutter I want to know if it is a good practice to segregate the elements of Any page like HOME to different Classes or DART files.

If the answer is positive, I need some help with that.

I am aware that I have to Include the pages in both Mother and daughter .dart pages to each other. Where I am confused is how much should I mention for a part of a page. (please forgive my nativity if there any)

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AppName',
      home: MyHomePage(),
    );

What should I return? The Material App already runs the Mother or main page so how much to be included? Or should I just Code the elements Like Row and Column and Card etc...

If the latter is true then how should I call them? Will those be automatically called when The MAIN .dart is executed?

~Addition~

Can I return any Layout Widget(Row/Column/Card) out of nothing !!

like

class MyHomePage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return Row(
        children: <Widget>[

(I think it is logical because all the queries will be ultimately forwarded to MAIN.dart)

Any help is appreciated.

2 Answers

Yes you can create many directories and arrange your Dart files in it like services, model and config. As you call the main.dart the other Classes will not certainly be on main.dart, let me put this this way, maon.dart = >homepage.dart => productPage.dart=>.......

it is just navigation while navigation to some parameters classes be sure to parse the parameters

If I understand your question correctly, let me answer with an example:

Say your main.dart is as follows:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AppName',
      home: MyHomePage(),
    );
  }
}

and your home_page.dart is:

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("AppName"),
      ),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          CustomWidget1(),
          CustomWidget2(),
        ],
      ),
    );
  }
}

Then CustomWidget1 can be (in a file named custom_widget_1.dart):

class CustomWidget1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text("CustomWidget1"),
    );
  }
}

Then CustomWidget2 can be (in a file named custom_widget_2.dart):

class CustomWidget2 extends StatefulWidget {
  CustomWidget2({Key key}) : super(key: key);

  @override
  _CustomWidget2State createState() => _CustomWidget2State();
}

class _CustomWidget2State extends State<CustomWidget2> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text("CustomWidget2"),
    );
  }
}
Related