0
0
Fluttermobile~5 mins

BuildContext in Flutter

Choose your learning style9 modes available
Introduction

BuildContext helps Flutter know where a widget is in the app's widget tree. It lets widgets find and use information from their surroundings.

When you want to get the size or theme of the current screen.
When you need to navigate to another screen from a button press.
When you want to find a parent widget to get some data or call a method.
When you want to show a popup or dialog related to the current widget.
When you want to rebuild or update parts of the UI based on user actions.
Syntax
Flutter
Widget build(BuildContext context) {
  // use context here
  return Container();
}

BuildContext is passed to the build method of widgets.

You use context to access theme, navigation, or parent widgets.

Examples
Use context to get the current theme and style text.
Flutter
Widget build(BuildContext context) {
  final theme = Theme.of(context);
  return Text('Hello', style: theme.textTheme.headlineMedium);
}
Use context to navigate to another screen.
Flutter
onPressed: () {
  Navigator.of(context).pushNamed('/next');
}
Use context to show a message at the bottom of the screen.
Flutter
final scaffold = ScaffoldMessenger.of(context);
scaffold.showSnackBar(SnackBar(content: Text('Hi!')));
Sample App

This app shows a button. When you tap it, it uses BuildContext to get the app's primary color from the theme and shows it in a message at the bottom.

Flutter
import 'package:flutter/material.dart';

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

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

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('BuildContext Example')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            final theme = Theme.of(context);
            final snackBar = SnackBar(
              content: Text('Primary color is: ${theme.colorScheme.primary}'),
            );
            ScaffoldMessenger.of(context).showSnackBar(snackBar);
          },
          child: Text('Show Primary Color'),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Always use the BuildContext passed to the current widget's build method or callbacks.

Do not use BuildContext from widgets that are no longer in the tree; it can cause errors.

BuildContext helps widgets communicate with their parents and the app environment.

Summary

BuildContext tells Flutter where a widget is in the widget tree.

Use it to access theme, navigation, and parent widgets.

It is passed to the build method and many callbacks.