Bird
Raised Fist0
Fluttermobile~20 mins

BuildContext in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: BuildContext Demo Screen
This screen demonstrates how to use BuildContext to show a SnackBar and navigate between screens.
Target UI
┌───────────────────────────────┐
│ BuildContext Demo             │
├───────────────────────────────┤
│                               │
│ [Show SnackBar]               │
│                               │
│ [Go to Next Screen]           │
│                               │
└───────────────────────────────┘
Add a button labeled 'Show SnackBar' that shows a SnackBar with a message using BuildContext.
Add a button labeled 'Go to Next Screen' that navigates to a new screen using BuildContext.
The next screen should have a simple text 'Next Screen' and a back button.
Starter Code
Flutter
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'BuildContext Demo',
      home: const HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('BuildContext Demo')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // TODO: Add 'Show SnackBar' button here
            // TODO: Add 'Go to Next Screen' button here
          ],
        ),
      ),
    );
  }
}

// TODO: Create NextScreen widget here
Task 1
Task 2
Task 3
Solution
Flutter
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'BuildContext Demo',
      home: const HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('BuildContext Demo')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ElevatedButton(
              onPressed: () {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('Hello from SnackBar!')),
                );
              },
              child: const Text('Show SnackBar'),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).push(
                  MaterialPageRoute(builder: (context) => const NextScreen()),
                );
              },
              child: const Text('Go to Next Screen'),
            ),
          ],
        ),
      ),
    );
  }
}

class NextScreen extends StatelessWidget {
  const NextScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Next Screen')),
      body: const Center(
        child: Text('Next Screen'),
      ),
    );
  }
}

This example shows how to use BuildContext to interact with the widget tree.

We use ScaffoldMessenger.of(context) to show a SnackBar on the current screen.

We use Navigator.of(context).push() to navigate to a new screen.

The NextScreen widget is a simple page with a back button automatically provided by the AppBar.

This teaches how BuildContext helps find the right place in the widget tree to perform actions like showing messages or navigation.

Final Result
Completed Screen
┌───────────────────────────────┐
│ BuildContext Demo             │
├───────────────────────────────┤
│                               │
│ [Show SnackBar]               │
│                               │
│ [Go to Next Screen]           │
│                               │
└───────────────────────────────┘

-- After tapping 'Show SnackBar' --
┌───────────────────────────────┐
│ BuildContext Demo             │
├───────────────────────────────┤
│                               │
│ [Show SnackBar]               │
│                               │
│ [Go to Next Screen]           │
│                               │
│ ┌─────────────────────────┐ │
│ │ Hello from SnackBar!     │ │
│ └─────────────────────────┘ │
└───────────────────────────────┘

-- After tapping 'Go to Next Screen' --
┌───────────────────────────────┐
│ Next Screen                  ◀│
├───────────────────────────────┤
│                               │
│          Next Screen           │
│                               │
└───────────────────────────────┘
Tap 'Show SnackBar' button: A SnackBar with message 'Hello from SnackBar!' appears at the bottom.
Tap 'Go to Next Screen' button: The app navigates to the Next Screen with a back arrow in the AppBar.
Tap back arrow on Next Screen: Returns to the BuildContext Demo screen.
Stretch Goal
Add a FloatingActionButton that shows a dialog with a TextField and a button to display the entered text in a SnackBar using BuildContext.
💡 Hint
Use showDialog with context, TextEditingController to get input, and ScaffoldMessenger.of(context) to show SnackBar.

Practice

(1/5)
1. What does BuildContext represent in Flutter?
easy
A. The color scheme of the app
B. The location of a widget in the widget tree
C. The size of the device screen
D. The state of a button widget

Solution

  1. Step 1: Understand the role of BuildContext

    BuildContext tells Flutter where a widget is located in the widget tree, which helps access parent widgets and resources.
  2. Step 2: Eliminate unrelated options

    Size, color scheme, and button state are not represented by BuildContext.
  3. Final Answer:

    The location of a widget in the widget tree -> Option B
  4. Quick Check:

    BuildContext = widget location [OK]
Hint: BuildContext shows widget position in the tree [OK]
Common Mistakes:
  • Confusing BuildContext with device size
  • Thinking BuildContext holds UI colors
  • Assuming BuildContext stores widget state
2. Which of the following is the correct way to access the theme data using BuildContext inside a widget's build method?
easy
A. Theme.of(context)
B. Theme.get(context)
C. context.theme()
D. ThemeData(context)

Solution

  1. Step 1: Recall Flutter's theme access syntax

    Flutter uses Theme.of(context) to get theme data from the widget tree.
  2. Step 2: Check other options for correctness

    Other options are not valid Flutter syntax for accessing theme data.
  3. Final Answer:

    Theme.of(context) -> Option A
  4. Quick Check:

    Theme access = Theme.of(context) [OK]
Hint: Use Theme.of(context) to get theme data [OK]
Common Mistakes:
  • Using incorrect method names like Theme.get
  • Trying to call theme as a method on context
  • Creating ThemeData with context argument
3. What will happen if you call Navigator.of(context).pop() inside a widget's build method?
medium
A. The app navigates to a new screen
B. Nothing happens because pop() is ignored in build
C. The current screen will close immediately
D. A runtime error occurs due to calling pop in build

Solution

  1. Step 1: Understand Navigator.of(context).pop()

    This command closes the current screen by popping it from the navigation stack.
  2. Step 2: Consider calling pop() inside build()

    Calling pop() during build causes a runtime error because navigation changes should not happen while building widgets.
  3. Final Answer:

    A runtime error occurs due to calling pop in build -> Option D
  4. Quick Check:

    pop() in build = runtime error [OK]
Hint: Avoid navigation calls inside build method [OK]
Common Mistakes:
  • Assuming pop() works safely in build
  • Thinking pop() does nothing in build
  • Confusing pop() with pushing new screens
4. Given this code snippet inside a widget:
void showMessage() {
  final snackBar = SnackBar(content: Text('Hello'));
  ScaffoldMessenger.of(context).showSnackBar(snackBar);
}

@override
Widget build(BuildContext context) {
  return ElevatedButton(
    onPressed: showMessage,
    child: Text('Press'),
  );
}

What is the likely problem here?
medium
A. Using context from build inside showMessage causes an error
B. SnackBar content must be a String, not Text widget
C. ElevatedButton cannot be used inside build method
D. showSnackBar is not a method of ScaffoldMessenger

Solution

  1. Step 1: Identify context usage in showMessage()

    The method uses context but it is not passed as a parameter, so it refers to the widget's field or outer scope.
  2. Step 2: Understand context scope in Flutter

    Using the context from build inside another method without passing it can cause errors because context may not be valid or accessible.
  3. Final Answer:

    Using context from build inside showMessage causes an error -> Option A
  4. Quick Check:

    Context must be passed to callbacks [OK]
Hint: Pass context explicitly to methods needing it [OK]
Common Mistakes:
  • Assuming context is always accessible everywhere
  • Thinking SnackBar content must be String
  • Believing ElevatedButton can't be in build
  • Confusing ScaffoldMessenger methods
5. You want to open a new screen when a button is pressed. Which is the best way to use BuildContext to navigate safely inside the button's onPressed callback?
hard
A. Use setState() to change the screen instead of Navigator
B. Create a new BuildContext inside the callback and call Navigator.push()
C. Pass the BuildContext from the build method to the callback and use Navigator.of(context).push()
D. Call Navigator.push() without any context

Solution

  1. Step 1: Understand navigation requires BuildContext

    Navigator needs a valid BuildContext from the widget tree to push a new screen.
  2. Step 2: Use context passed to build method

    Passing the context from build to the callback ensures the context is valid and navigation works safely.
  3. Step 3: Eliminate incorrect options

    Creating a new context is not possible; Navigator.push requires context; setState changes UI state but not navigation.
  4. Final Answer:

    Pass the BuildContext from the build method to the callback and use Navigator.of(context).push() -> Option C
  5. Quick Check:

    Use passed context for navigation [OK]
Hint: Always use passed context for navigation calls [OK]
Common Mistakes:
  • Trying to create new BuildContext manually
  • Calling Navigator.push without context
  • Using setState to navigate screens
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard