skip to Main Content

can someone explain me in details the function of build method in flutter?

  1. Why are we using it?
  2. If we don’t use it what will happen?

A.

class MyApp extends statelessWidget{
  Widget build(BuildCintext context) {
    return Container (
        color: Colors.white,
        height: 300,
        weight: 300,
        child: Text("This is a container ") ,
  }
}

B.

void main() {
  runApp(
      Container (
        color: Colors.white,
        height: 300,
        weight: 300,
        child: Text("This is a container ") ,
      ),
  };
}
  1. The code A has a build method but code B doesn’t have but both of them display same output, so what are differences between them?? if build method is important why code B doesn’t have it?

I tried search on many websites still have many questions flutter

2

Answers


  1. You are asking two separate questions:

    1. What is the build method?

    2. Why does the code in sample B work without a build method?

    1:

    Every StatefulWidget and StatelessWidget has a build method that describes what the UI should look like for the given context.

    basically,
    The build method is responsible for describing a widget’s part in the widget tree.

    2:

    the reason why in your example it runs without the build method is The runApp function’s primary purpose is to take a given widget and attach it to the screen, making it the root of the widget tree. It doesn’t need to "build" anything, and doesnt require a stateful/stateless widget.

    Login or Signup to reply.
  2. The build is an interface usually used to draw a visual implementation of a Stateful or a Stateless Widgets.

    If you think of the build as the relation of a screen to a computer, you can figure out you don’t need it to make a widget work. just like servers don’t need screens. But a widget without a build can have all it needs on its initialization and can be a virtual element, without any visual interface, but still be part of how the app works.

    In your example, the Container is actually a Widget, and immediately, there is a build method being run on the background to draw that component, and all the properties set for it, even if immediately it seems there is no build.

    Answering your 3rd question, the code is similar, but the second one is slightly more efficient because you’re not creating a middle component that has no effect on the global output, despite the visual content being exactly the same between them, because the widget you create on your first example, has the exact same visual content as the component from the second example.

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