Created with <3 with dartpad.dev.
Created
November 14, 2023 23:13
-
-
Save hongsw/187d57c142b9198aa2d8c975f9c1e1e9 to your computer and use it in GitHub Desktop.
상태관리 1page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
// 1페이지에서 1개의 클래스에서 같은 상황이라서 어렵지않게 상태를 공유 할 수 있다. | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Todo App', | |
home: TodoListScreen(), | |
); | |
} | |
} | |
class TodoListScreen extends StatefulWidget { | |
@override | |
_TodoListScreenState createState() => _TodoListScreenState(); | |
} | |
class _TodoListScreenState extends State<TodoListScreen> { | |
List<String> todos = []; | |
String todoStatus = "Status : "; | |
TextEditingController controller = TextEditingController(); | |
void addTodo() { | |
setState(() { | |
todos.add(controller.text); | |
controller.clear(); | |
todoStatus = "Status : ${todos.length}"; | |
}); | |
} | |
void removeTodo(int index) { | |
setState(() { | |
todos.removeAt(index); | |
todoStatus = "Status : ${todos.length}"; | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: Text('Todo List')), | |
body: Column( | |
children: [ | |
Text(todoStatus), | |
Expanded( | |
child: ListView.builder( | |
itemCount: todos.length, | |
itemBuilder: (context, index) { | |
return ListTile( | |
title: Text(todos[index]), | |
trailing: IconButton( | |
icon: Icon(Icons.delete), | |
onPressed: () => removeTodo(index), | |
), | |
); | |
}, | |
), | |
), | |
TextField( | |
controller: controller, | |
decoration: InputDecoration( | |
labelText: 'Add todo', | |
suffixIcon: IconButton( | |
icon: Icon(Icons.add), | |
onPressed: addTodo, | |
), | |
), | |
), | |
], | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment