Skip to content

Instantly share code, notes, and snippets.

@debuggerx01
Created October 14, 2022 02:39
Show Gist options
  • Save debuggerx01/5e05196de9186a2217ea7047e49072a5 to your computer and use it in GitHub Desktop.
Save debuggerx01/5e05196de9186a2217ea7047e49072a5 to your computer and use it in GitHub Desktop.
flutter_del_edit_list_test
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class Bean {
String text;
Bean(this.text);
}
class Item extends StatefulWidget {
const Item({
Key? key,
required this.bean,
required this.onDelete,
required this.onSubmit,
}) : super(key: key);
final Bean bean;
final ValueChanged<Bean> onDelete;
final ValueChanged<String> onSubmit;
@override
State<Item> createState() => _ItemState();
}
class _ItemState extends State<Item> {
late TextEditingController _textEditController;
final FocusNode _node = FocusNode();
@override
void initState() {
_textEditController = TextEditingController(text: widget.bean.text);
_node.addListener(() {
if (!_node.hasFocus) {
widget.onSubmit(_textEditController.text);
}
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Row(
children: [
Flexible(
child: TextField(
controller: _textEditController,
focusNode: _node,
),
),
IconButton(
onPressed: () => widget.onDelete(widget.bean),
icon: const Icon(Icons.delete),
),
],
);
}
}
final initData = [
Bean('asd'),
Bean('123'),
Bean('zxc'),
Bean('456'),
Bean('qwe'),
];
class _MyHomePageState extends State<MyHomePage> {
var data = [...initData];
_reset() {
setState(() {
data = [...initData];
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) => Item(
key: UniqueKey(),
bean: data[index],
onDelete: (value) {
setState(() {
data.remove(value);
});
},
onSubmit: (value) {
setState(() {
data[index] = Bean(value);
});
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: _reset,
tooltip: 'Reset',
child: const Icon(Icons.recycling),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment