Welcome to this tutorial on Widgets in Flutter! The goal of this tutorial is to introduce you to the concept of widgets in Flutter, understand how they work, and why they are so central to Flutter apps.
By the end of this tutorial, you will be able to:
Widgets are the basic building blocks of a Flutter app's user interface. Each widget is an immutable declaration of part of the user interface. Widgets can either be stateless or stateful.
A stateless widget describes part of the user interface which can depend on configuration information in the widget itself and in the widget’s parent but does not depend on any runtime state.
Stateless widgets are created, then drawn once and never redrawn. They are static and cannot change once rendered.
Stateful widgets maintain state that might change during the lifetime of the widget. Implementing a stateful widget requires at least two classes: 1) a StatefulWidget class that creates an instance of 2) a State class.
Stateful widgets are dynamic. The user interface can change dynamically when the state changes.
Here are some code examples to help you understand widgets better:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Hello Flutter',
home: Scaffold(
appBar: AppBar(
title: Text('Hello Flutter'),
),
body: Center(
child: Text('Hello Flutter'),
),
),
);
}
}
In this code snippet:
When you run this code, it will display a simple app with an app bar and text in the center of the screen that says 'Hello Flutter'.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
int counter = 0;
void incrementCounter() {
setState(() {
counter++;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Counter App',
home: Scaffold(
appBar: AppBar(
title: Text('Counter App'),
),
body: Center(
child: Text('Counter: $counter'),
),
floatingActionButton: FloatingActionButton(
onPressed: incrementCounter,
child: Icon(Icons.add),
),
),
);
}
}
In this code snippet:
When you run this code, it will display a simple counter app. The counter increases each time you press the floating action button.
In this tutorial, we covered:
Next steps for learning:
Additional resources:
Solutions and explanations for these exercises are left for you to try. Remember, practice is key to mastering Flutter widgets. Keep practicing and building awesome apps!