fnotes/lib/notes_app.dart
Marco 10ad73c940 Adding persistence
This commit adds persistence.
Notes are added to a sqlite database, can be deleted and are read at app
start.
2024-03-29 17:14:47 +01:00

132 lines
4.0 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fnotes/note.dart';
import 'package:fnotes/persistence_bloc.dart';
import 'package:fnotes/theme_bloc.dart';
class NotesApp extends StatefulWidget {
const NotesApp({
super.key,
});
@override
State<NotesApp> createState() => _NotesAppState();
}
class _NotesAppState extends State<NotesApp> {
final phraseController = TextEditingController();
@override
void initState() {
context.read<PersistenceBloc>().add(LoadNotesEvent());
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Your notes:'),
actions: [
IconButton(
icon: const Icon(Icons.light_mode),
onPressed: () {
context.read<ThemeBloc>().add(ThemeEvent());
},
)
],
),
body: BlocBuilder<ThemeBloc, ThemeState>(
builder: (context, state) {
return BlocBuilder<PersistenceBloc, PersistenceState>(
builder: (context, blocState) {
return ListView.builder(
itemCount: blocState.notes.length,
itemBuilder: (context, index) {
return Dismissible(
onDismissed: (direction) {
context.read<PersistenceBloc>().add(NoteDismissed(
Note.withId(
id: blocState.notes[index].id,
content: blocState.notes[index].content)));
},
key: ValueKey(blocState.notes[index]),
child: Card(
elevation: 5,
color: state.theme.colorScheme.primaryContainer,
child: SizedBox(
height: 50,
child: Padding(
padding: const EdgeInsets.only(left: 20),
child: Align(
alignment: Alignment.centerLeft,
child: Text(
blocState.notes[index].content,
style: TextStyle(
color:
state.theme.colorScheme.onPrimaryContainer),
),
),
),
),
),
);
},
);
});
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
final newNote = showEnterItemDialog(context);
newNote.then(
(value) {
if (value != null && value.isNotEmpty) {
context
.read<PersistenceBloc>()
.add(NoteEntered(Note(content: value)));
}
},
);
},
child: const Icon(Icons.add)),
);
}
Future<String?> showEnterItemDialog(BuildContext context) {
return showDialog<String>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('New list item'),
content: TextField(
onSubmitted: (val) {
Navigator.pop(context, val);
phraseController.clear();
},
autofocus: true,
controller: phraseController,
decoration: InputDecoration(
hintText: 'Remember me!',
suffixIcon: IconButton(
onPressed: () {
Navigator.pop(context, phraseController.value.text);
phraseController.clear();
},
icon: const Icon(Icons.check),
)),
),
actions: <Widget>[
TextButton(
child: const Text('Cancel'),
onPressed: () {
Navigator.pop(context);
},
),
],
);
},
);
}
}