skip to Main Content

in default flutter project runApp function it countain the MyApp class as aparameter so when we run app It’s normal for the content of the class MyApp and content of StatelessWidget class to appear , but how the run app function get content of others classes like MyHomepage class and StatefullWidget class.

import 'package:flutter/material.dart'; 

void main() => runApp(MyApp()); 


class MyApp extends StatelessWidget { 

 @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', 
theme: ThemeData(
  primarySwatch: Colors.blue, ), 

home: MyHomePage(title: 'Flutter Demo Home Page'), ); }} 

class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); 

final String title; 

@override 

_MyHomePageState createState() => _MyHomePageState();} 

class _MyHomePageState extends State<MyHomePage> { 

int _counter = 0; 

void _incrementCounter() { 
setState(() { 


_counter++; }); } 

@override

 Widget build(BuildContext context) { 


 return Scaffold( appBar: AppBar(


 title: Text(widget.title), ), body: Center(

 

mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ 

Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.display1, ), ], ), ),

 floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add);}}

3

Answers


  1. Chosen as BEST ANSWER

    I found out the answer yesterday and it is that the relationship between the runApp function and MyHomePage class is that parameter named home in MyApp class takes MyHomePage class as its value


  2. Flutter is based on a widget tree. To the runApp method only the root of the tree is passed. In this example, MyApp is the root of this tree and all other widgets are referenced only by being in MyApp or its children. For example, here MyHomePage is a child of MyApp. Away from the pages, the "smaller" widgets like Text or Container are also part of this tree and referenced in the single pages.

    Do you have a more specific question about what you don’t understand or have I already answered your question?

    Login or Signup to reply.
  3. Whatever valid widget you pass inside runApp() will be displayed and it will be considered as the root widget of the app tree.

    So, it is best to use a widget which returns a MaterialApp() widget as this will constitute the window frame of your app on which other widgets will be displayed as pages.

    These page widgets that will be routed to the MaterialApp widget should in turn return a Scaffold() widget.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search