Search the site
APP
Prefer classes to functions? Extend DVClassWidget for pages and reusable widgets alike.
A class and a functional widget build, route and render the same way.
ON THIS PAGE
Write a page as a class
Write a reusable widget as a class
Keep state in signals
Choose a class or a function
Put @DVPage on a class that extends DVClassWidget, in a file under lib/pages. The file path is the route, as for a function page, and the generated DVRoutes member points at it.
// lib/pages/team.dart is served at /team.
@DVPage(title: 'Our team')
class const TeamListPage({super.key}) extends DVClassWidget {
@override
Widget build(BuildContext context) => const DVBox.list(<Widget>[
DVText('Our team'),
MemberCard('Ada', role: 'Engineering'),
MemberCard('Grace', role: 'Design'),
]);
}Copy code to clipboard
Give the class a const primary constructor that takes super.key.
The page is server-rendered on the web, selectable and readable by screen readers, like every other page.
A loading or error companion (about.loading.dart, about.error.dart) can be a class too.
A widget used inside pages is also a DVClassWidget. It has no @DVPage, so it gets no route. Its constructor parameters are its inputs.
// lib/components/member_card.dart
class const MemberCard(final String name, {super.key, final String role = ''})
extends DVClassWidget {
@override
Widget build(BuildContext context) => DVBox.list(<Widget>[
DVText(name).modifier(const DVModifier().fontWeight(.w600)),
if (role.isNotEmpty) DVText(role),
]);
}Copy code to clipboard
Not StatelessWidget or StatefulWidget
dartvel build reports a Flutter widget class in your app as DV-CONV-012. Extend DVClassWidget, or annotate a function with @DVFunctionalWidget.
A class widget has no State class and no setState. Create a signal with context.signal in build, and read its value there: the widget redraws when the value changes.
// State is a signal read in build, not a State class and setState.
class const LikeButton({super.key}) extends DVClassWidget {
@override
Widget build(BuildContext context) {
final DVSignal<int> likes = context.signal(0);
return DVText('Like (${likes.value})').modifier(
DVModifier().onTap(() => likes.value = likes.value + 1),
);
}
}Copy code to clipboard
Derived signals, globals and reactive data models work the same in a class as in a function. The State page explains them.
Both shapes are first-class. Every sample in these docs has a Function tab and a Class tab.
One app can mix them: a class page can show functional widgets, and the other way round.
pageScrollToTop: true on a DVClassWidget adds the "Back to top" button, the same as on @DVFunctionalWidget.
FSL-1.1-MIT licensed. Built with Dartvel.
Dartvel is made by
To the bottom