In this tutorial, we aim to provide a comprehensive guide on how to use widgets in Flutter.
By the end of this tutorial, you will learn:
- What a widget is in Flutter
- Different types of widgets and their usage
- How to use them in a Flutter application
Prerequisites: Basic understanding of Flutter and Dart Programming language. Familiarity with object-oriented programming will be helpful.
In Flutter, everything is a widget. Widgets are the basic building blocks of a Flutter application's user interface. It describes what the view should look like given its current configuration and state.
There are mainly two types of widgets in Flutter:
1. Stateless Widgets: These are static widgets. They describe a part of the user interface which can't change over time.
2. Stateful Widgets: These are dynamic widgets. They can change dynamically, i.e., they can redraw themselves multiple times within their life cycle.
Widgets are used in a tree of nodes called the Widget Tree. This tree consists of two types of objects: Widgets and Elements. A Widget is an immutable description of part of the user interface; an Element is a mutable instantiation of a Widget over time.
Here's an example of a stateless widget that creates a simple Material App.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
// Creating a stateless widget
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Stateless Widget Example'),
),
body: Center(
child: Text('Hello World!'),
),
),
);
}
}
Here's an example of a stateful widget that creates a counter.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
// Creating a stateful widget
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: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Stateful Widget Example'),
),
body: Center(
child: Text('Counter value: $_counter'),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
),
);
}
}
In this tutorial, we have learned about widgets, the two types of widgets, and how to use them in a Flutter app.
For further learning, you can explore more about managing state in stateful widgets and the widget lifecycle.
Solutions:
1. This exercise is similar to the Stateless Widget example provided above.
2. & 3. These exercises are similar to the Stateful Widget example provided above. Just replace the counter with the required functionality.
Happy Fluttering!