Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "context" of "Widget build(BuildContext context)" mean in Flutter?

Tags:

flutter

dart

TL;DR:
Is it the second parameter of build method or, name declaration of the BuildContext parameter in a conventional way?

I'm learning the basic syntax of build method in Flutter by breaking down each element of "Widget build(BuildContext context)".

My understanding so far is below:

  • @override: annotation
  • Widget build() {}: build method returns a widget
  • BuildContext: a parameter/argument that contains information about the location in the tree at which this widget is being built

However, it's not been clear what the last word "context" exactly means even after I read related SO questions and official documents.

What I made sure so far is that the name "context" is changeable to whatever you want, meaning it doesn't have to be the same name as "context".

like image 401
Baka Avatar asked Feb 01 '19 13:02

Baka


People also ask

What is widget build BuildContext context?

BuildContext is a locator that is used to track each widget in a tree and locate them and their position in the tree. The BuildContext of each widget is passed to their build method. Remember that the build method returns the widget tree a widget renders. Each BuildContext is unique to a widget.

What does context mean in Flutter?

A context is nothing else but a reference to the location of a Widget within the tree structure of all the Widgets which are built. In short, think of a context as the part of Widgets tree where the Widget is attached to this tree. A context only belongs to one widget.

Is every widget have its own BuildContext?

Each widget has its own BuildContext, which becomes the parent of the widget returned by the StatelessWidget.


1 Answers

From the docs, BuildContext is:

A handle to the location of a widget in the widget tree.

context is a BuildContext instance which gets passed to the builder of a widget in order to let it know where it is inside the Widget Tree of your app.

One of the common uses is passing it to the of method when using an Inherited Widget.

Calling Something.of(context), for example, returns the Something relative to the closest widget in the tree that can provide you that Something.

You can read more about BuildContext here in the docs.

like image 165
magicleon94 Avatar answered Oct 01 '22 00:10

magicleon94