Apps that react when you tap · 4 h
Collect and check what the user types · 4 h
Move between screens, dialogs and tabs · 4 h
Make the app beautiful and alive · 4 h
Data that can change while the app runs: a counter, a switch, the items in a cart.
Tells Flutter: data changed, redraw the screen.
Likes, quantity buttons, dark mode switches, tabs, quizzes, games.
A StatelessWidget never changes after it is drawn: a logo, a title. A StatefulWidget has data that changes: a counter, a switch.
Only build(). Same input, same picture.
Two classes: the widget and its State. Data lives in the State class.
Does anything on this widget change when the user taps? Yes: Stateful.
stful and press Enter. The whole skeleton appears.The number lives in the State class. Pressing the button runs setState, Flutter calls build() again, and the new number appears.
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int count = 0; // the state
@override
Widget build(BuildContext context) {
return Column(mainAxisAlignment: MainAxisAlignment.center, children: [
Text('$count', style: const TextStyle(fontSize: 56)),
ElevatedButton(
onPressed: () {
setState(() { count++; }); // change + redraw
},
child: const Text('Add one'),
),
]);
}
}
void main() {
runApp(const MaterialApp(home: Scaffold(body: Counter())));
}onPressed runs your code.
Inside setState(() { ... }) you change the variable.
This widget needs a new picture.
The widget is rebuilt with the new data and the screen updates.
State is not only numbers. A bool remembers on/off. A List remembers cart items or tasks. Any change inside setState redraws.
bool liked = false;
List<String> items = [];
// toggle
setState(() => liked = !liked);
// add to a list
setState(() => items.add('New task'));
// remove from a list
setState(() => items.removeAt(0));Inside children you can write if (condition) Widget. The widget appears only when the state says so. The ? : operator chooses between two widgets.
Column(children: [
Switch(value: show, onChanged: (v) => setState(() => show = v)),
if (show) const Text('Hello, I am visible'),
show ? const Icon(Icons.visibility) : const Icon(Icons.visibility_off),
])class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int count = 0;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(child: Text('$count', style: const TextStyle(fontSize: 64))),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => count++),
child: const Icon(Icons.add),
),
);
}
void main() => runApp(const MaterialApp(home: Counter()));!liked.class Like extends StatefulWidget {
const Like({super.key});
@override
State<Like> createState() => _LikeState();
}
class _LikeState extends State<Like> {
bool liked = false;
@override
Widget build(BuildContext context) => Scaffold(
body: Center(child: IconButton(
iconSize: 80,
icon: Icon(liked ? Icons.favorite : Icons.favorite_border,
color: liked ? Colors.red : Colors.grey),
onPressed: () => setState(() => liked = !liked),
)),
);
}
void main() => runApp(const MaterialApp(home: Like()));class Faq extends StatefulWidget {
const Faq({super.key});
@override
State<Faq> createState() => _FaqState();
}
class _FaqState extends State<Faq> {
bool open = false;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('FAQ')),
body: Padding(padding: const EdgeInsets.all(20), child: Column(children: [
ListTile(
title: const Text('What is the course fee?'),
trailing: Icon(open ? Icons.expand_less : Icons.expand_more),
onTap: () => setState(() => open = !open),
),
if (open) const Text('The fee is Rs 24,000 and can be paid in 3 instalments.'),
])),
);
}
void main() => runApp(const MaterialApp(home: Faq()));class Mode extends StatefulWidget {
const Mode({super.key});
@override
State<Mode> createState() => _ModeState();
}
class _ModeState extends State<Mode> {
bool dark = false;
@override
Widget build(BuildContext context) => Scaffold(
backgroundColor: dark ? Colors.grey.shade900 : Colors.white,
body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
Icon(dark ? Icons.dark_mode : Icons.light_mode, size: 60, color: dark ? Colors.yellow : Colors.orange),
Text(dark ? 'Night' : 'Day', style: TextStyle(fontSize: 30, color: dark ? Colors.white : Colors.black)),
Switch(value: dark, onChanged: (v) => setState(() => dark = v)),
])),
);
}
void main() => runApp(const MaterialApp(home: Mode()));class Qty extends StatefulWidget {
const Qty({super.key});
@override
State<Qty> createState() => _QtyState();
}
class _QtyState extends State<Qty> {
int qty = 1;
final int price = 245;
@override
Widget build(BuildContext context) => Scaffold(
body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
const Text('Atta 5 kg', style: TextStyle(fontSize: 24)),
Row(mainAxisSize: MainAxisSize.min, children: [
IconButton(icon: const Icon(Icons.remove_circle), onPressed: () { if (qty > 1) setState(() => qty--); }),
Text('$qty', style: const TextStyle(fontSize: 28)),
IconButton(icon: const Icon(Icons.add_circle), onPressed: () => setState(() => qty++)),
]),
Text('Total: Rs ${qty * price}', style: const TextStyle(fontSize: 20, color: Colors.green)),
])),
);
}
void main() => runApp(const MaterialApp(home: Qty()));class Cart extends StatefulWidget {
const Cart({super.key});
@override
State<Cart> createState() => _CartState();
}
class _CartState extends State<Cart> {
final names = ['Atta 5 kg', 'Rice 10 kg', 'Dal 1 kg'];
final prices = [245, 380, 140];
final qty = [1, 1, 1];
@override
Widget build(BuildContext context) {
int total = 0;
for (var i = 0; i < names.length; i++) { total += prices[i] * qty[i]; }
return Scaffold(
appBar: AppBar(title: const Text('Cart')),
body: Column(children: [
for (var i = 0; i < names.length; i++) ListTile(
title: Text(names[i]), subtitle: Text('Rs ${prices[i]}'),
trailing: Row(mainAxisSize: MainAxisSize.min, children: [
IconButton(icon: const Icon(Icons.remove), onPressed: () => setState(() { if (qty[i] > 0) qty[i]--; })),
Text('${qty[i]}'),
IconButton(icon: const Icon(Icons.add), onPressed: () => setState(() => qty[i]++)),
])),
const Divider(),
Text('Total: Rs $total', style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold)),
]),
);
}
}
void main() => runApp(const MaterialApp(home: Cart()));class Tabs extends StatefulWidget {
const Tabs({super.key});
@override
State<Tabs> createState() => _TabsState();
}
class _TabsState extends State<Tabs> {
int sel = 0;
final tabs = ['Food', 'Drinks', 'Sweets'];
final data = [['Litti', 'Dhuska'], ['Lassi', 'Sattu sharbat'], ['Thekua', 'Peda']];
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Menu')),
body: Column(children: [
Row(mainAxisAlignment: MainAxisAlignment.center, children: [
for (var i = 0; i < tabs.length; i++) Padding(padding: const EdgeInsets.all(6),
child: ChoiceChip(label: Text(tabs[i]), selected: sel == i, onSelected: (_) => setState(() => sel = i))),
]),
for (final d in data[sel]) ListTile(leading: const Icon(Icons.restaurant), title: Text(d)),
]),
);
}
void main() => runApp(const MaterialApp(home: Tabs()));class Todo extends StatefulWidget {
const Todo({super.key});
@override
State<Todo> createState() => _TodoState();
}
class _TodoState extends State<Todo> {
final tasks = ['Buy vegetables', 'Finish Flutter homework'];
int n = 0;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text('Tasks (${tasks.length})')),
body: ListView.builder(
itemCount: tasks.length,
itemBuilder: (c, i) => ListTile(
title: Text(tasks[i]),
trailing: IconButton(icon: const Icon(Icons.delete, color: Colors.red),
onPressed: () => setState(() => tasks.removeAt(i))),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() { n++; tasks.add('New task $n'); }),
child: const Icon(Icons.add),
),
);
}
void main() => runApp(const MaterialApp(home: Todo()));class Quiz extends StatefulWidget {
const Quiz({super.key});
@override
State<Quiz> createState() => _QuizState();
}
class _QuizState extends State<Quiz> {
final qs = [
['Capital of Jharkhand?', 'Ranchi', 'Patna', 'Dhanbad', '0'],
['Flutter uses which language?', 'Java', 'Dart', 'Swift', '1'],
['State change method?', 'setState', 'runApp', 'build', '0'],
];
int i = 0, score = 0;
void pick(int a) => setState(() { if (a == int.parse(qs[i][4])) score++; i++; });
@override
Widget build(BuildContext context) {
if (i >= qs.length) {
return Scaffold(body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
const Icon(Icons.emoji_events, size: 70, color: Colors.amber),
Text('Score: $score / ${qs.length}', style: const TextStyle(fontSize: 28)),
Text('${(score * 100 / qs.length).toStringAsFixed(0)}%'),
ElevatedButton(onPressed: () => setState(() { i = 0; score = 0; }), child: const Text('Try again')),
])));
}
return Scaffold(
appBar: AppBar(title: Text('Question ${i + 1} of ${qs.length}')),
body: Padding(padding: const EdgeInsets.all(20), child: Column(children: [
LinearProgressIndicator(value: i / qs.length),
const SizedBox(height: 24),
Text(qs[i][0], style: const TextStyle(fontSize: 22)),
const SizedBox(height: 16),
for (var k = 1; k <= 3; k++) Padding(padding: const EdgeInsets.only(bottom: 8),
child: SizedBox(width: double.infinity, child: OutlinedButton(onPressed: () => pick(k - 1), child: Text(qs[i][k])))),
])),
);
}
}
void main() => runApp(const MaterialApp(home: Quiz()));class Game extends StatefulWidget {
const Game({super.key});
@override
State<Game> createState() => _GameState();
}
class _GameState extends State<Game> {
List<String> b = List.filled(9, '');
bool xTurn = true;
String winner = '';
final lines = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]];
void tap(int i) {
if (b[i] != '' || winner != '') return;
setState(() {
b[i] = xTurn ? 'X' : 'O';
xTurn = !xTurn;
for (final l in lines) {
if (b[l[0]] != '' && b[l[0]] == b[l[1]] && b[l[1]] == b[l[2]]) winner = b[l[0]];
}
});
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(winner != '' ? '$winner wins!' : (xTurn ? 'X turn' : 'O turn'))),
body: Column(children: [
Expanded(child: GridView.count(crossAxisCount: 3, padding: const EdgeInsets.all(16),
crossAxisSpacing: 6, mainAxisSpacing: 6,
children: [for (var i = 0; i < 9; i++) InkWell(onTap: () => tap(i),
child: Container(color: Colors.indigo.shade50, alignment: Alignment.center,
child: Text(b[i], style: const TextStyle(fontSize: 44))))])),
ElevatedButton(onPressed: () => setState(() { b = List.filled(9, ''); winner = ''; xTurn = true; }), child: const Text('Reset')),
]),
);
}
void main() => runApp(const MaterialApp(home: Game()));Use it when data changes after a tap.
Change data inside it, build() runs again.
Switches, likes, show/hide.
Todo and cart items.
Show widgets depending on state.
State + logic = tic-tac-toe, quiz.
Name, mobile number, email, password.
Checkbox for terms, Radio for gender, Dropdown for city.
Show "Enter 10 digit mobile number" before submit.
A TextEditingController holds what the user typed. Read it with controller.text when the button is pressed.
TextInputType.phone, .emailAddress, .number. obscureText: true hides a password.final nameCtrl = TextEditingController();
TextField(
controller: nameCtrl,
decoration: const InputDecoration(
labelText: 'Student name',
hintText: 'e.g. Rohit Singh',
prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(),
),
)
// read the text later
print(nameCtrl.text);onChanged runs on every key press. Use it for live search, character counters and live previews.
TextField(
onChanged: (value) {
setState(() => name = value);
},
)
Text('Hello, $name!')Checkbox(value: agree, onChanged: (v) => setState(() => agree = v!)): yes/no, can pick many.
An on/off setting: notifications, dark mode.
Pick exactly ONE of a group: gender, payment method. All radios share one groupValue.
DropdownButton chooses one item from a long list: city, class.
A validator returns an error text, or null when the value is fine. validate() runs all validators and shows the red messages.
final key = GlobalKey<FormState>();
Form(
key: key,
child: Column(children: [
TextFormField(
validator: (v) {
if (v == null || v.length != 10) return 'Enter 10 digit mobile number';
return null; // null means OK
},
),
ElevatedButton(
onPressed: () {
if (key.currentState!.validate()) { /* submit */ }
},
child: const Text('Submit'),
),
]),
)Slider(value: v, min: 0, max: 100, onChanged: ...): volume, price range, marks.
Opens a calendar to pick a date of birth or a booking day.
Pick a time for an appointment reminder.
Pickers prevent typing mistakes like "32/13/2020".
class NameBox extends StatefulWidget {
const NameBox({super.key});
@override
State<NameBox> createState() => _NameBoxState();
}
class _NameBoxState extends State<NameBox> {
final c = TextEditingController();
String shown = '';
@override
Widget build(BuildContext context) {
return Padding(padding: const EdgeInsets.all(20), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
TextField(controller: c, decoration: const InputDecoration(labelText: 'Your name', border: OutlineInputBorder())),
const SizedBox(height: 12),
ElevatedButton(onPressed: () => setState(() => shown = c.text), child: const Text('Show')),
Text(shown, style: const TextStyle(fontSize: 24)),
]));
}
}
void main() => runApp(const MaterialApp(home: Scaffold(body: NameBox())));class Live extends StatefulWidget {
const Live({super.key});
@override
State<Live> createState() => _LiveState();
}
class _LiveState extends State<Live> {
String name = '';
@override
Widget build(BuildContext context) {
return Padding(padding: const EdgeInsets.all(20), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
TextField(onChanged: (v) => setState(() => name = v), decoration: const InputDecoration(labelText: 'Type your name')),
const SizedBox(height: 20),
Text(name.isEmpty ? 'Hello!' : 'Hello, $name!', style: const TextStyle(fontSize: 28)),
Text('${name.length} letters'),
]));
}
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Live())));class Terms extends StatefulWidget {
const Terms({super.key});
@override
State<Terms> createState() => _TermsState();
}
class _TermsState extends State<Terms> {
bool agree = false;
@override
Widget build(BuildContext context) {
return Padding(padding: const EdgeInsets.all(20), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
CheckboxListTile(
title: const Text('I accept the terms and conditions'),
value: agree,
onChanged: (v) => setState(() => agree = v!),
),
ElevatedButton(onPressed: agree ? () {} : null, child: const Text('Continue')),
]));
}
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Terms())));class Settings extends StatefulWidget {
const Settings({super.key});
@override
State<Settings> createState() => _SettingsState();
}
class _SettingsState extends State<Settings> {
bool notify = true;
bool sound = false;
@override
Widget build(BuildContext context) {
return ListView(children: [
SwitchListTile(title: const Text('Notifications'), subtitle: Text(notify ? 'On' : 'Off'), value: notify, onChanged: (v) => setState(() => notify = v)),
SwitchListTile(title: const Text('Sound'), subtitle: Text(sound ? 'On' : 'Off'), value: sound, onChanged: (v) => setState(() => sound = v)),
]);
}
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Settings())));class Pay extends StatefulWidget {
const Pay({super.key});
@override
State<Pay> createState() => _PayState();
}
class _PayState extends State<Pay> {
String method = 'UPI';
@override
Widget build(BuildContext context) {
return Column(mainAxisAlignment: MainAxisAlignment.center, children: [
const Text('Payment method', style: TextStyle(fontSize: 22)),
RadioListTile<String>(title: const Text('UPI'), value: 'UPI', groupValue: method, onChanged: (v) => setState(() => method = v!)),
RadioListTile<String>(title: const Text('Card'), value: 'Card', groupValue: method, onChanged: (v) => setState(() => method = v!)),
RadioListTile<String>(title: const Text('Cash on delivery'), value: 'COD', groupValue: method, onChanged: (v) => setState(() => method = v!)),
Text('You chose: $method'),
]);
}
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Pay())));class Fee extends StatefulWidget {
const Fee({super.key});
@override
State<Fee> createState() => _FeeState();
}
class _FeeState extends State<Fee> {
final fees = {'Flutter': 18000, 'Python': 15000, 'Web Design': 12000};
String course = 'Flutter';
@override
Widget build(BuildContext context) {
return Padding(padding: const EdgeInsets.all(24), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
DropdownButton<String>(
value: course,
isExpanded: true,
items: fees.keys.map((k) => DropdownMenuItem(value: k, child: Text(k))).toList(),
onChanged: (v) => setState(() => course = v!),
),
const SizedBox(height: 20),
Text('Fee: Rs ${fees[course]}', style: const TextStyle(fontSize: 26, color: Colors.green)),
]));
}
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Fee())));class Signup extends StatefulWidget {
const Signup({super.key});
@override
State<Signup> createState() => _SignupState();
}
class _SignupState extends State<Signup> {
final key = GlobalKey<FormState>();
String msg = '';
@override
Widget build(BuildContext context) {
return Form(key: key, child: Padding(padding: const EdgeInsets.all(20), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
TextFormField(decoration: const InputDecoration(labelText: 'Mobile number'), keyboardType: TextInputType.phone,
validator: (v) => (v == null || v.length != 10) ? 'Enter 10 digit mobile number' : null),
TextFormField(decoration: const InputDecoration(labelText: 'Password'), obscureText: true,
validator: (v) => (v == null || v.length < 6) ? 'At least 6 characters' : null),
const SizedBox(height: 16),
ElevatedButton(onPressed: () => setState(() => msg = key.currentState!.validate() ? 'Form is valid' : 'Please fix errors'), child: const Text('Sign up')),
Text(msg),
])));
}
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Signup())));class Marks extends StatefulWidget {
const Marks({super.key});
@override
State<Marks> createState() => _MarksState();
}
class _MarksState extends State<Marks> {
double marks = 60;
@override
Widget build(BuildContext context) {
final grade = marks >= 75 ? 'A' : marks >= 50 ? 'B' : 'C';
return Padding(padding: const EdgeInsets.all(24), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
Text('Marks: ${marks.round()}', style: const TextStyle(fontSize: 28)),
Slider(value: marks, min: 0, max: 100, divisions: 20, label: '${marks.round()}', onChanged: (v) => setState(() => marks = v)),
Text('Grade $grade', style: const TextStyle(fontSize: 36, color: Colors.indigo)),
]));
}
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Marks())));class Admission extends StatefulWidget {
const Admission({super.key});
@override
State<Admission> createState() => _AdmissionState();
}
class _AdmissionState extends State<Admission> {
final key = GlobalKey<FormState>();
final name = TextEditingController();
String cls = 'Class 10';
String gender = 'Male';
bool agree = false;
String done = '';
@override
Widget build(BuildContext context) {
return SingleChildScrollView(padding: const EdgeInsets.all(18), child: Form(key: key, child: Column(children: [
const SizedBox(height: 30),
TextFormField(controller: name, decoration: const InputDecoration(labelText: 'Student name', border: OutlineInputBorder()),
validator: (v) => v!.trim().isEmpty ? 'Name is required' : null),
const SizedBox(height: 10),
DropdownButtonFormField<String>(value: cls, items: ['Class 8', 'Class 9', 'Class 10'].map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(), onChanged: (v) => setState(() => cls = v!)),
Row(children: [for (final g in ['Male', 'Female']) Expanded(child: RadioListTile<String>(title: Text(g), value: g, groupValue: gender, onChanged: (v) => setState(() => gender = v!)))]),
CheckboxListTile(title: const Text('I agree to the rules'), value: agree, onChanged: (v) => setState(() => agree = v!)),
ElevatedButton(onPressed: () {
if (key.currentState!.validate() && agree) setState(() => done = 'Admitted: ${name.text} ($gender), $cls');
}, child: const Text('Submit')),
if (done != '') Card(color: Colors.green.shade50, child: Padding(padding: const EdgeInsets.all(12), child: Text(done))),
])));
}
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Admission())));class Steps extends StatefulWidget {
const Steps({super.key});
@override
State<Steps> createState() => _StepsState();
}
class _StepsState extends State<Steps> {
int step = 0;
final titles = ['Personal', 'Contact', 'Confirm'];
@override
Widget build(BuildContext context) {
final pages = [
const Column(children: [TextField(decoration: InputDecoration(labelText: 'Full name')), TextField(decoration: InputDecoration(labelText: 'Age'))]),
const Column(children: [TextField(decoration: InputDecoration(labelText: 'Mobile')), TextField(decoration: InputDecoration(labelText: 'City'))]),
const Center(child: Column(children: [Icon(Icons.check_circle, size: 70, color: Colors.green), Text('All set!', style: TextStyle(fontSize: 22))])),
];
return Padding(padding: const EdgeInsets.fromLTRB(20, 50, 20, 20), child: Column(children: [
Text('Step ${step + 1} of 3: ${titles[step]}', style: const TextStyle(fontSize: 20)),
const SizedBox(height: 8),
LinearProgressIndicator(value: (step + 1) / 3),
const SizedBox(height: 20),
pages[step],
const Spacer(),
Row(children: [
if (step > 0) OutlinedButton(onPressed: () => setState(() => step--), child: const Text('Back')),
const Spacer(),
if (step < 2) ElevatedButton(onPressed: () => setState(() => step++), child: const Text('Next')),
]),
]));
}
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Steps())));controller.text and onChanged.
Checkbox, Switch, Radio, Dropdown keep a value in state.
GlobalKey + validate() for checking input.
Return error text or null.
Safe numbers and dates.
A step number decides what is shown.
Tap a product, a new page slides in; the back button returns.
Home, Search, Profile tabs; side menu with Settings and Log out.
"Delete this item?" confirmation before something important.
Flutter keeps screens in a stack, like plates. push puts a new screen on top. pop removes the top one and shows the one below.
Open a new screen on top of the current one.
Close the current screen and go back.
On Android the phone back button pops automatically.
MaterialPageRoute describes the new screen and gives it the standard slide animation. Every Scaffold with an AppBar also gets a free back arrow.
// open the details screen
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const DetailsPage()),
);
},
child: const Text('Open details'),
)
// on the details screen: go back
ElevatedButton(
onPressed: () => Navigator.pop(context),
child: const Text('Back'),
)To send data, give the new screen constructor arguments. To get data back, await the push and send the value with pop(context, value).
// send data: put it in the constructor Navigator.push(context, MaterialPageRoute( builder: (_) => DetailsPage(name: 'Litti Chokha', price: 120), )); // get a result back final ok = await Navigator.push<bool>(context, MaterialPageRoute(builder: (_) => const ConfirmPage())); // in ConfirmPage: Navigator.pop(context, true); // sends true back
A routes table gives every screen a name like a web address. Easier to read and change in big apps.
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => const HomePage(),
'/cart': (context) => const CartPage(),
'/profile': (context) => const ProfilePage(),
},
)
// anywhere in the app
Navigator.pushNamed(context, '/cart');These are not new screens but overlays. They sit above the page and are closed with Navigator.pop.
// dialog
showDialog(context: context, builder: (_) => AlertDialog(
title: const Text('Delete?'),
actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('No'))],
));
// snack bar (small message at the bottom)
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Saved')));
// bottom sheet
showModalBottomSheet(context: context, builder: (_) => const SizedBox(height: 200));3 to 5 main sections. Keep the selected index in state and show the matching page.
A side menu opened by the hamburger icon. Good for many rarely used items.
Swipeable tabs inside one screen: Chats, Status, Calls.
Bottom bar for the main areas; Drawer for extras like Settings and Help.
class Home extends StatelessWidget {
const Home({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(child: ElevatedButton(
child: const Text('Open About'),
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => const About())),
)),
);
}
class About extends StatelessWidget {
const About({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('About')),
body: Center(child: ElevatedButton(onPressed: () => Navigator.pop(context), child: const Text('Go back'))),
);
}
void main() => runApp(const MaterialApp(home: Home()));class Details extends StatelessWidget {
final String name; final int price;
const Details({super.key, required this.name, required this.price});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(name)),
body: Center(child: Text('Rs $price', style: const TextStyle(fontSize: 40))),
);
}
class Home extends StatelessWidget {
const Home({super.key});
@override
Widget build(BuildContext context) {
final items = {'Litti Chokha': 120, 'Dhuska': 60, 'Lassi': 40};
return Scaffold(
appBar: AppBar(title: const Text('Menu')),
body: ListView(children: items.entries.map((e) => ListTile(
title: Text(e.key), trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push(context, MaterialPageRoute(builder: (_) => Details(name: e.key, price: e.value))),
)).toList()),
);
}
}
void main() => runApp(const MaterialApp(home: Home()));class Pick extends StatelessWidget {
const Pick({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Select city')),
body: ListView(children: ['Ranchi', 'Patna', 'Jamshedpur'].map((c) => ListTile(
title: Text(c), onTap: () => Navigator.pop(context, c))).toList()),
);
}
class Home extends StatefulWidget {
const Home({super.key});
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
String city = 'No city chosen';
@override
Widget build(BuildContext context) => Scaffold(
body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
Text(city, style: const TextStyle(fontSize: 24)),
ElevatedButton(onPressed: () async {
final r = await Navigator.push<String>(context, MaterialPageRoute(builder: (_) => const Pick()));
if (r != null) setState(() => city = r);
}, child: const Text('Choose city')),
])),
);
}
void main() => runApp(const MaterialApp(home: Home()));class Page extends StatelessWidget {
final String title; final String next;
const Page(this.title, this.next, {super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(child: ElevatedButton(onPressed: () => Navigator.pushNamed(context, next), child: Text('Go to $next'))),
);
}
void main() {
runApp(MaterialApp(
initialRoute: '/',
routes: {
'/': (c) => const Page('Home', '/cart'),
'/cart': (c) => const Page('Cart', '/profile'),
'/profile': (c) => const Page('Profile', '/'),
},
));
}class Home extends StatelessWidget {
const Home({super.key});
@override
Widget build(BuildContext context) => Scaffold(
body: Center(child: ElevatedButton(
child: const Text('Delete account'),
onPressed: () => showDialog(context: context, builder: (ctx) => AlertDialog(
title: const Text('Delete account?'),
content: const Text('This cannot be undone.'),
actions: [
TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('No')),
TextButton(onPressed: () {
Navigator.pop(ctx);
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Account deleted')));
}, child: const Text('Yes')),
],
)),
)),
);
}
void main() => runApp(const MaterialApp(home: Home()));pages[index]. Tapping a tab calls setState with the new index.class Shell extends StatefulWidget {
const Shell({super.key});
@override
State<Shell> createState() => _ShellState();
}
class _ShellState extends State<Shell> {
int i = 0;
final pages = const [Center(child: Text('Home page')), Center(child: Text('Search page')), Center(child: Text('Profile page'))];
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Ranchi Mart')),
body: pages[i],
bottomNavigationBar: BottomNavigationBar(
currentIndex: i,
onTap: (v) => setState(() => i = v),
items: const [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'),
BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Profile'),
],
),
);
}
void main() => runApp(const MaterialApp(home: Shell()));class Home extends StatefulWidget {
const Home({super.key});
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
String page = 'Dashboard';
Widget item(IconData i, String t) => ListTile(leading: Icon(i), title: Text(t),
onTap: () { setState(() => page = t); Navigator.pop(context); });
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(page)),
drawer: Drawer(child: ListView(children: [
const DrawerHeader(decoration: BoxDecoration(color: Colors.indigo),
child: Text('Nandan Kumar\nBrainBit Infotech, Ranchi', style: TextStyle(color: Colors.white, fontSize: 20))),
item(Icons.dashboard, 'Dashboard'), item(Icons.school, 'Courses'), item(Icons.settings, 'Settings'),
])),
body: Center(child: Text('$page screen', style: const TextStyle(fontSize: 26))),
);
}
void main() => runApp(const MaterialApp(home: Home()));void main() {
runApp(MaterialApp(home: DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
title: const Text('Class Group'),
bottom: const TabBar(tabs: [Tab(text: 'Chats'), Tab(text: 'Status'), Tab(text: 'Calls')]),
),
body: const TabBarView(children: [
Center(child: Text('Chats list')),
Center(child: Text('Status updates')),
Center(child: Text('Call history')),
]),
),
)));
}class Detail extends StatelessWidget {
final String name;
const Detail(this.name, {super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(name)),
body: Center(child: ElevatedButton(onPressed: () => Navigator.pop(context, name), child: const Text('Add to cart'))),
);
}
class Shop extends StatefulWidget {
const Shop({super.key});
@override
State<Shop> createState() => _ShopState();
}
class _ShopState extends State<Shop> {
final cart = <String>[];
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text('Shop (cart: ${cart.length})'), actions: [
IconButton(icon: const Icon(Icons.shopping_cart), onPressed: () => showDialog(context: context,
builder: (_) => AlertDialog(title: const Text('Your cart'), content: Text(cart.isEmpty ? 'Empty' : cart.join(', '))))),
]),
body: ListView(children: ['School Bag', 'Water Bottle', 'Notebook Set'].map((n) => ListTile(
title: Text(n), trailing: const Icon(Icons.chevron_right),
onTap: () async {
final r = await Navigator.push<String>(context, MaterialPageRoute(builder: (_) => Detail(n)));
if (r != null) setState(() => cart.add(r));
},
)).toList()),
);
}
void main() => runApp(const MaterialApp(home: Shop()));class Login extends StatefulWidget {
const Login({super.key});
@override
State<Login> createState() => _LoginState();
}
class _LoginState extends State<Login> {
final user = TextEditingController();
final pass = TextEditingController();
String err = '';
@override
Widget build(BuildContext context) => Scaffold(
body: Padding(padding: const EdgeInsets.all(24), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
const Text('Welcome', style: TextStyle(fontSize: 30)),
TextField(controller: user, decoration: const InputDecoration(labelText: 'User (try: ranchi)')),
TextField(controller: pass, obscureText: true, decoration: const InputDecoration(labelText: 'Password (try: 1234)')),
const SizedBox(height: 12),
ElevatedButton(onPressed: () {
if (user.text == 'ranchi' && pass.text == '1234') {
Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => Home(user.text)));
} else { setState(() => err = 'Wrong user or password'); }
}, child: const Text('Login')),
Text(err, style: const TextStyle(color: Colors.red)),
])),
);
}
class Home extends StatelessWidget {
final String user;
const Home(this.user, {super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Home'), automaticallyImplyLeading: false, actions: [
IconButton(icon: const Icon(Icons.logout), onPressed: () => Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => const Login()))),
]),
body: Center(child: Text('Hello, $user!', style: const TextStyle(fontSize: 28))),
);
}
void main() => runApp(const MaterialApp(home: Login()));push adds a screen, pop removes it.
Constructor arguments.
await push, pop(context, value).
Named routes in MaterialApp.
Dialog, SnackBar, BottomSheet.
BottomNavigationBar, Drawer, TabBar.
Change a value and Flutter animates it for you: size, colour, opacity.
Change one colour in one place and the whole app follows.
The same app looks right on a small phone, a big phone and a tablet.
Put a duration and change a value in setState. The widget glides from the old value to the new one. You write no animation code at all.
AnimatedContainer(
duration: const Duration(milliseconds: 500),
curve: Curves.easeInOut,
width: big ? 200 : 100,
height: big ? 200 : 100,
decoration: BoxDecoration(
color: big ? Colors.orange : Colors.blue,
borderRadius: BorderRadius.circular(big ? 100 : 8),
),
)opacity: show ? 1 : 0 fades a widget in and out.
When its child changes, the old one fades out and the new one fades in. Give the child a different key.
Fades between exactly two children, for example show more / show less.
easeIn, easeOut, bounceOut, elasticOut change how the motion feels.
An AnimationController counts from 0 to 1 over a duration. AnimatedBuilder redraws a widget on every tick. Use it for repeating or multi-step animations.
class _PulseState extends State<Pulse> with SingleTickerProviderStateMixin {
late AnimationController c;
@override
void initState() {
super.initState();
c = AnimationController(vsync: this, duration: const Duration(seconds: 1))
..repeat(reverse: true);
}
@override
void dispose() { c.dispose(); super.dispose(); }
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: c,
builder: (context, child) => Container(
width: 60 + c.value * 60, height: 60 + c.value * 60,
decoration: const BoxDecoration(color: Colors.red, shape: BoxShape.circle),
),
);
}ThemeData sets colours, fonts and shapes for every widget. colorSchemeSeed builds a full matching palette from one colour. darkTheme + themeMode give dark mode.
MaterialApp(
theme: ThemeData(
colorSchemeSeed: Colors.indigo,
useMaterial3: true,
brightness: Brightness.light,
),
darkTheme: ThemeData(
colorSchemeSeed: Colors.indigo,
brightness: Brightness.dark,
),
themeMode: ThemeMode.system, // or .light / .dark
home: const HomePage(),
)
// read the theme anywhere
Theme.of(context).colorScheme.primary
Theme.of(context).textTheme.titleLargeMediaQuery tells you about the whole screen. LayoutBuilder tells you the space your widget got. Use them to switch layouts: 1 column on a phone, 2 on a tablet.
// screen size and settings
final size = MediaQuery.of(context).size;
final isSmall = size.width < 360;
final top = MediaQuery.of(context).padding.top; // status bar
// size of the parent box
LayoutBuilder(builder: (context, box) {
if (box.maxWidth > 600) return const TabletLayout();
return const PhoneLayout();
})class Grow extends StatefulWidget {
const Grow({super.key});
@override
State<Grow> createState() => _GrowState();
}
class _GrowState extends State<Grow> {
bool big = false;
@override
Widget build(BuildContext context) {
return Center(child: GestureDetector(
onTap: () => setState(() => big = !big),
child: AnimatedContainer(
duration: const Duration(milliseconds: 500),
curve: Curves.easeInOut,
width: big ? 220 : 100, height: big ? 220 : 100,
decoration: BoxDecoration(color: big ? Colors.orange : Colors.indigo, borderRadius: BorderRadius.circular(big ? 110 : 12)),
alignment: Alignment.center,
child: Text(big ? 'Big' : 'Tap', style: const TextStyle(color: Colors.white, fontSize: 20)),
),
));
}
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Grow())));class Fade extends StatefulWidget {
const Fade({super.key});
@override
State<Fade> createState() => _FadeState();
}
class _FadeState extends State<Fade> {
bool show = true;
@override
Widget build(BuildContext context) {
return Column(mainAxisAlignment: MainAxisAlignment.center, children: [
AnimatedOpacity(
opacity: show ? 1 : 0,
duration: const Duration(milliseconds: 600),
child: const Icon(Icons.wb_sunny, size: 100, color: Colors.orange),
),
ElevatedButton(onPressed: () => setState(() => show = !show), child: Text(show ? 'Hide' : 'Show')),
]);
}
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Fade())));class App extends StatefulWidget {
const App({super.key});
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
bool dark = false;
@override
Widget build(BuildContext context) => MaterialApp(
theme: ThemeData(colorSchemeSeed: Colors.indigo),
darkTheme: ThemeData(colorSchemeSeed: Colors.indigo, brightness: Brightness.dark),
themeMode: dark ? ThemeMode.dark : ThemeMode.light,
home: Scaffold(
appBar: AppBar(title: const Text('Theme demo')),
body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
const Text('Hello Ranchi', style: TextStyle(fontSize: 28)),
Switch(value: dark, onChanged: (v) => setState(() => dark = v)),
ElevatedButton(onPressed: () {}, child: const Text('A button')),
])),
),
);
}
void main() => runApp(const App());class Info extends StatelessWidget {
const Info({super.key});
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Scaffold(body: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
Text('Width: ${size.width.toStringAsFixed(0)} Height: ${size.height.toStringAsFixed(0)}'),
const SizedBox(height: 16),
Container(width: size.width * 0.8, height: 60, color: Colors.teal, alignment: Alignment.center,
child: const Text('80% of width', style: TextStyle(color: Colors.white))),
])));
}
}
void main() => runApp(const MaterialApp(home: Info()));void main() {
runApp(MaterialApp(home: Scaffold(body: Center(child: Container(
width: 280, height: 150, padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: const LinearGradient(colors: [Color(0xFF6A11CB), Color(0xFF2575FC)], begin: Alignment.topLeft, end: Alignment.bottomRight),
borderRadius: BorderRadius.circular(20),
boxShadow: const [BoxShadow(color: Colors.black38, blurRadius: 14, offset: Offset(0, 8))],
),
child: const Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
Text('Festival Offer', style: TextStyle(color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold)),
Text('Up to 40% off on Ranchi Mart', style: TextStyle(color: Colors.white70)),
]),
)))));
}void main() {
runApp(MaterialApp(home: Scaffold(
appBar: AppBar(title: const Text('Responsive grid')),
body: LayoutBuilder(builder: (context, box) {
final cols = box.maxWidth > 600 ? 4 : box.maxWidth > 300 ? 3 : 2;
return Column(children: [
Padding(padding: const EdgeInsets.all(8), child: Text('Width ${box.maxWidth.toStringAsFixed(0)} so $cols columns')),
Expanded(child: GridView.count(crossAxisCount: cols, padding: const EdgeInsets.all(8), crossAxisSpacing: 8, mainAxisSpacing: 8,
children: List.generate(8, (i) => Container(color: Colors.indigo.shade100, alignment: Alignment.center, child: Text('${i + 1}')))),
),
]);
}),
)));
}class Count extends StatefulWidget {
const Count({super.key});
@override
State<Count> createState() => _CountState();
}
class _CountState extends State<Count> {
int n = 0;
@override
Widget build(BuildContext context) {
return Center(child: Column(mainAxisSize: MainAxisSize.min, children: [
AnimatedSwitcher(
duration: const Duration(milliseconds: 400),
child: Text('$n', key: ValueKey(n), style: const TextStyle(fontSize: 90, fontWeight: FontWeight.bold, color: Colors.indigo)),
),
ElevatedButton(onPressed: () => setState(() => n++), child: const Text('Add')),
]));
}
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Count())));class Pulse extends StatefulWidget {
const Pulse({super.key});
@override
State<Pulse> createState() => _PulseState();
}
class _PulseState extends State<Pulse> with SingleTickerProviderStateMixin {
late AnimationController c;
@override
void initState() {
super.initState();
c = AnimationController(vsync: this, duration: const Duration(milliseconds: 900))..repeat(reverse: true);
}
@override
void dispose() { c.dispose(); super.dispose(); }
@override
Widget build(BuildContext context) => Center(child: AnimatedBuilder(
animation: c,
builder: (context, child) => Container(
width: 60 + c.value * 70, height: 60 + c.value * 70, alignment: Alignment.center,
decoration: BoxDecoration(color: Colors.red.withOpacity(0.4 + c.value * 0.6), shape: BoxShape.circle),
child: const Icon(Icons.favorite, color: Colors.white),
),
));
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Pulse())));class Onboard extends StatefulWidget {
const Onboard({super.key});
@override
State<Onboard> createState() => _OnboardState();
}
class _OnboardState extends State<Onboard> {
int i = 0;
final pages = [['\u{1F4DA}', 'Learn Flutter', 'Short lessons for every level'], ['\u{1F4F1}', 'Build apps', 'Practice with real projects'], ['\u{1F3C6}', 'Get certified', 'Show your skills to employers']];
@override
Widget build(BuildContext context) {
return Padding(padding: const EdgeInsets.all(28), child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
AnimatedSwitcher(
duration: const Duration(milliseconds: 350),
child: Column(key: ValueKey(i), children: [
Text(pages[i][0], style: const TextStyle(fontSize: 90)),
Text(pages[i][1], style: const TextStyle(fontSize: 26, fontWeight: FontWeight.bold)),
Text(pages[i][2]),
]),
),
const SizedBox(height: 30),
Row(mainAxisAlignment: MainAxisAlignment.center, children: [
for (var k = 0; k < 3; k++) AnimatedContainer(
duration: const Duration(milliseconds: 300), margin: const EdgeInsets.all(4),
width: k == i ? 28 : 10, height: 10,
decoration: BoxDecoration(color: k == i ? Colors.indigo : Colors.grey.shade400, borderRadius: BorderRadius.circular(5)),
),
]),
const SizedBox(height: 30),
ElevatedButton(onPressed: () => setState(() => i = i < 2 ? i + 1 : 0), child: Text(i < 2 ? 'Next' : 'Start again')),
]));
}
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Onboard())));class Prog extends StatefulWidget {
const Prog({super.key});
@override
State<Prog> createState() => _ProgState();
}
class _ProgState extends State<Prog> {
double pct = 0.25;
@override
Widget build(BuildContext context) {
return Center(child: Card(margin: const EdgeInsets.all(20), child: Padding(padding: const EdgeInsets.all(20), child: Column(mainAxisSize: MainAxisSize.min, children: [
const Text('Flutter Course Progress', style: TextStyle(fontSize: 20)),
const SizedBox(height: 16),
TweenAnimationBuilder<double>(
tween: Tween<double>(begin: 0, end: pct),
duration: const Duration(milliseconds: 800),
builder: (context, v, child) => Column(children: [
LinearProgressIndicator(value: v, minHeight: 14),
const SizedBox(height: 8),
Text('${(v * 100).toStringAsFixed(0)}%', style: const TextStyle(fontSize: 32, color: Colors.indigo)),
]),
),
const SizedBox(height: 12),
Row(mainAxisAlignment: MainAxisAlignment.center, children: [
OutlinedButton(onPressed: () => setState(() => pct = 0.25), child: const Text('25%')),
const SizedBox(width: 8),
OutlinedButton(onPressed: () => setState(() => pct = 0.6), child: const Text('60%')),
const SizedBox(width: 8),
ElevatedButton(onPressed: () => setState(() => pct = 1.0), child: const Text('100%')),
]),
]))));
}
}
void main() => runApp(const MaterialApp(home: Scaffold(body: Prog())));Animated* widgets glide between values.
Fades between different children using keys.
Full control; always dispose.
One place for colours and fonts, plus dark mode.
Whole-screen size and settings.
Space the parent gives; switch layouts.