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.