|
import 'package:flutter/material.dart'; |
|
import 'package:flutter_bloc/flutter_bloc.dart'; |
|
|
|
class NameCubit extends Cubit<String> { |
|
NameCubit() : super(''); |
|
|
|
void addNewName(String name) => emit(name); |
|
} |
|
|
|
const Color darkBlue = Color.fromARGB(255, 18, 32, 47); |
|
|
|
void main() { |
|
runApp(MyApp()); |
|
} |
|
|
|
class MyApp extends StatelessWidget { |
|
@override |
|
Widget build(BuildContext context) { |
|
return BlocProvider( |
|
create: (context) => NameCubit(), |
|
child: MaterialApp( |
|
theme: ThemeData.dark().copyWith( |
|
scaffoldBackgroundColor: darkBlue, |
|
), |
|
debugShowCheckedModeBanner: false, |
|
home: MyWidget(), |
|
), |
|
); |
|
} |
|
} |
|
|
|
class MyWidget extends StatelessWidget { |
|
final _controller = TextEditingController(); |
|
@override |
|
Widget build(BuildContext context) { |
|
// read cubit from context |
|
final cubit = context.read<NameCubit>(); |
|
return Scaffold( |
|
body: Center( |
|
// BlocBuilder internally get the cubit from the context |
|
child: BlocListener<NameCubit, String>( |
|
listener: (BuildContext context, String state) { |
|
if (state.isNotEmpty) { |
|
showDialog( |
|
context: context, |
|
builder: (context) => AlertDialog( |
|
title: Text('Hello, $state!'), |
|
actions: [ |
|
TextButton( |
|
onPressed: () { |
|
Navigator.pop(context); |
|
}, |
|
child: Text('OK'), |
|
), |
|
], |
|
), |
|
); |
|
} |
|
}, |
|
child: Padding( |
|
padding: const EdgeInsets.all(8.0), |
|
child: Row( |
|
children: [ |
|
Expanded( |
|
child: TextField( |
|
controller: _controller, |
|
decoration: InputDecoration(labelText: 'Enter your name'), |
|
), |
|
), |
|
ElevatedButton( |
|
onPressed: () { |
|
cubit.addNewName(_controller.text.trim()); |
|
_controller.clear(); |
|
}, |
|
child: Text('Submit'), |
|
), |
|
], |
|
), |
|
), |
|
), |
|
), |
|
); |
|
} |
|
} |
Articles about:
https://verygood.ventures/blog/very-good-flutter-architecture
https://leancode.co/blog/feature-based-flutter-architecture