Skip to content

Instantly share code, notes, and snippets.

@happyharis
Created May 16, 2021 00:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save happyharis/87849cf85b8406ec2f12432a90c881e1 to your computer and use it in GitHub Desktop.
Save happyharis/87849cf85b8406ec2f12432a90c881e1 to your computer and use it in GitHub Desktop.
Learn Flutter Workshop - Todo App v2
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primarySwatch: Colors.indigo),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final todos = <String>['Learn Flutter', 'Create Todo App'];
final textController = TextEditingController();
final editController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Todos'),
),
body: Padding(
padding: const EdgeInsets.all(18.0),
child: Column(
children: [
TextField(
controller: textController,
decoration: InputDecoration(border: OutlineInputBorder()),
),
for (var todo in todos)
ListTile(
leading: Text(todo),
trailing: Row(mainAxisSize: MainAxisSize.min, children: [
OutlinedButton(
onPressed: () => setState(() => todos.remove(todo)),
child: Text('Done'),
),
SizedBox(width: 5),
OutlinedButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Edit todo: $todo'),
content: TextField(
controller: editController,
decoration: InputDecoration(
border: OutlineInputBorder(),
),
),
actions: [
ElevatedButton(
onPressed: () => setState(() {
todos.replaceRange(
todos.indexOf(todo),
todos.indexOf(todo) +1,
[editController.text],
);
Navigator.of(context).pop();
}),
child: Text('Save'),
),
OutlinedButton(
onPressed: () => Navigator.of(context).pop(),
child: Text('Cancel'),
),
],
);
},
);
},
child: Text('Edit'),
),
]),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
if (textController.text.isEmpty) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Please enter some text 🥺'),
);
},
);
} else {
setState(() {
todos.add(textController.text);
textController.clear();
});
}
},
child: Icon(Icons.add),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment