The “context” issue in Flutter

 


It’s been about 8 months since I started working with Flutter, I can say that I didn’t have much difficulty in understanding the general writing principles and widget tree.

The reason why I preferred Flutter was that it is becoming increasingly popular and can be output on different platforms with the same code. Indeed, I was able to develop tiny applications in a short time and this motivated me even more.

But there is a context issue that I have to say that I used it by heart at first :) Fortunately, as I worked on it and used it in different applications and widget structures, I understood its logic and decided to write about it first because I thought that there might be people like me who have difficulties.

What is context?

The first thing we need to know about context is that it is present in the widget tree in our application and it is a context as in the dictionary sense. Within this context, it controls the current state, location and interaction with other widgets. In simpler terms, it refers to the context in which a widget exists.

What is BuildContext?

In order to better understand what a context is, it is very important to understand the BuildContext class it depends on.

BuildContext points to a point in the widget tree. This point contains the widget’s location, theme information and other context information. We use this structure to share information and state between widgets, use navigator methods, access theme information, and so on. This makes our application more modular, flexible and maintainable.

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

The code above is the first code that is automatically generated for us when creating a project in Flutter. Here we see that BuildContext is used as the parameter of the build method. Here “context” represents the context information from the place that calls this method.

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Example of BuildContext'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
// 'context' can be used here
showSnackBar(context);
},
child: Text('Show Snackbar'),
),
),
);
}

In this example, we show a snackbar using BuildContext. By passing the context to the showSnackBar method, we make the method use the current context in the widget tree.

Therefore, SnackBar detects where it is located in the widget tree, what its context is, where it is triggered from, and behaves accordingly. So shoxSnackBar gets its context from the context of the build method. That context, this context :).

As a result, making our Flutter application more sustainable and flexible depends on proper communication between widgets and we can use this very easily with the BuildContext structure.

I hope I was able to clear up some of the confusion and helped you a little bit.

Thank you.

Selin.

Flutter’da “context” Meselesi

 


Flutter çalışmaya başlayalı yaklaşık 8 ay kadar oldu, genel yazım prensiplerini, widget ağacını anlamakta pek zorlanmadım diyebilirim.

Flutter’ı tercih etmekteki sebebim ise giderek popüler olması ve aynı kodla farklı platformlarda çıktı alınabiliyor olmasıydı. Gerçekten de kısa sürede minik de olsa uygulamalar geliştirebildim ve bu beni daha da motive etti.

Fakat bir context meselesi var ki, bunu ilk başlarda ezbere kullandığımı söylemezsem olmaz :) Neyse ki üzerinde çalıştıkça, farklı uygulamalar ve widget yapılarında kullandıkça mantığını kavradım ve benim gibi zorlananlar olabileceğini düşündüğüm için ilk olarak bunun üzerine yazmaya karar verdim.

Context nedir?

context ile ilgili ilk bilmemiz gereken şey, uygulamamızdaki widget ağacında bulunması ve sözlük anlamında olduğu gibi bir bağlam. Bu bağlam içerisinde mevcut durumu, konumu ve diğer widget’lar ile etkileşimi kontrol ediyor. Daha basit anlatımla bir widget’in içinde bulunduğu bağlamı ifade ediyor.

BuildContext nedir?

context’in ne olduğunu daha iyi anlayabilmek için bağlı bulunduğu BuildContext sınıfını anlamak çok önemli.

BuildContext widget ağacında bir noktayı işaret eder. Bu noktada, widget’ın yeri, tema bilgileri ve diğer bağlam bilgileri de yer alır. Biz bu yapıyı kullanarak widget’lar arasındaki bilgi ve durumu paylaşır, navigator metodlarını kullanır, tema bilgilerine erişiriz, ve bunun gibi daha bir çok şey. Böylelikle uygulamamız daha modüler, esnek ve sürdürülebilir hale gelir.

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

Yukarıdaki kod, Flutter’da proje oluştururken bizim için otomatik olarak oluşturulan ilk kod. Burada build metodunun parametresi olarak BuildContext kullanıldığını görüyoruz. Burada “context” bu metodu çağıran yerden gelen bağlam bilgisini temsil ediyor.

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('BuildContext Örneği'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
// 'context' burada kullanılabilir
showSnackBar(context);
},
child: Text('Snackbar Göster'),
),
),
);
}

Bu örnekte, BuildContext’i kullanarak bir snackbar gösteriyoruz. showSnackBar metoduna context’i geçerek, metodun widget ağacındaki mevcut bağlamı kullanmasını sağlıyoruz.

Dolayısıyla SnackBar widget ağacının neresinde konumlandığını, bağlamının ne olduğunu, nereden tetiklendiğini bu context sayesinde tespit ederek buna göre davranıyor. Yani shoxSnackBar context’ini build metodunun context’inden alıyor. O context, bu context :).

Sonuç olarak geliştirdiğimiz Flutter uygulamamızın daha sürdürülebilir ve esnek olabilmesi widget’lar arasındaki düzgün iletişime bağlı ve bunu da BuildContext yapısıyla çok kolay bir şekilde kullanabiliyoruz.

Umarım mevcut kafa karışıklıklarını biraz olsun giderebilmişimdir ve faydam dokunmuştur.

Sevgiler.

Selin.