modulapp 1.1.1
modulapp: ^1.1.1 copied to clipboard
A simple base class to help you modularize your apps.
module_example #
This example shows how it's simple to modularize a Flutter app.
Here you'll find two modules: LoginModule & HomeModule.
Both are extending the ModuleRouter mixin and so they both define a list of routes.
The initial location page is "/login" and the login page will redirect you to "/home" if you provide a login name.
main.dart #
import 'package:flutter/material.dart';
import 'package:modulapp/modulapp.dart';
void main() {
final loginModule = LoginModule();
final homeModule = HomeModule();
runApp(
Material(
child: MaterialApp(
initialRoute: loginModule.routes.first.key,
routes: Map.fromEntries([loginModule, homeModule].routes),
),
),
);
}
class HomeModule extends Module with ModuleRouter<MapEntry<String, WidgetBuilder>> {
@override
final List<MapEntry<String, WidgetBuilder>> routes = [
MapEntry('/home', (context) => const HomeView()),
];
}
class HomeView extends StatelessWidget {
const HomeView({super.key});
@override
Widget build(BuildContext context) {
return CommonPage(
title: 'Home',
child: Text('WELCOME ${ModalRoute.of(context)?.settings.arguments}'),
);
}
}
class LoginModule extends Module with ModuleRouter<MapEntry<String, WidgetBuilder>> {
@override
final List<MapEntry<String, WidgetBuilder>> routes = [
MapEntry('/login', (context) => const LoginView()),
];
}
class LoginView extends StatefulWidget {
const LoginView({super.key});
@override
State<LoginView> createState() => _LoginViewState();
}
class _LoginViewState extends State<LoginView> {
final _formKey = GlobalKey<FormState>();
final _loginTextFieldController = TextEditingController();
void _onSubmit() {
_formKey.currentState?.save();
final isFormValid = _formKey.currentState?.validate() ?? false;
if (isFormValid) {
Navigator.of(context).pushNamed('/home', arguments: _loginTextFieldController.text);
}
}
@override
Widget build(BuildContext context) {
return CommonPage(
title: 'Login',
child: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: _loginTextFieldController,
decoration: const InputDecoration(hintText: 'Login'),
validator: (e) => e == null || e.isEmpty ? 'This field is required' : null,
onFieldSubmitted: (_) => _onSubmit(),
),
Padding(
padding: const EdgeInsets.only(top: 16.0),
child: ElevatedButton(onPressed: _onSubmit, child: const Text('Submit')),
),
],
),
),
);
}
}
class CommonPage extends StatelessWidget {
final String title;
final Widget child;
const CommonPage({super.key, required this.title, required this.child});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(title)),
body: Center(child: SizedBox(width: 400, child: child)),
);
}
}