主要差異為 DataCell 內的 Text 改成可編輯的 TextField。
components/post_table_with_search_and_edit.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:webservice_client/daos/shared_preferences_dao.dart';
import 'package:webservice_client/models/post.dart';
import 'package:http/http.dart' as http;
// ignore: must_be_immutable
class PostTableWithSearchAndEdit extends StatefulWidget {
PostTableWithSearchAndEdit(this.posts, {super.key});
List<Post> posts;
@override
State createState() {
return _PostTableWithSearchAndEdit();
}
}
class _PostTableWithSearchAndEdit extends State<PostTableWithSearchAndEdit> {
String filterInput = '';
List<Post> filteredPosts = [];
void changeFilteredPosts(String userInput) {
filterInput = userInput;
filteredPosts = widget.posts.where(
(element) {
if(userInput == '') {
return true;
}
else if(element.title.contains(userInput)) {
//print(element.title);
return true;
}
else {
return false;
}
},
).toList();
if(filteredPosts.isEmpty) {
filteredPosts.add(Post(0, 0, "查無資料", "查無資料"));
}
SharedPreferencesDao.setSearchKey(userInput);
}
@override
void initState() {
super.initState();
filterInput = SharedPreferencesDao.getSearchKey();
}
@override
Widget build(BuildContext context) {
if(filteredPosts.isEmpty) {
changeFilteredPosts(filterInput);
}
var searchTextEditingController = TextEditingController()..text = filterInput;
Widget searchBar = TextField(
controller: searchTextEditingController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter a search term'
),
onSubmitted: (userInput){
setState(() {
changeFilteredPosts(userInput);
});
},
);
// Convert object variables to data column list
List<String> columnNames = (jsonDecode(filteredPosts[0].toJsonObjectString()) as Map<String, dynamic>).keys.toList();
List<DataColumn> dataColumns = columnNames.map((key) {
return DataColumn(label: Text(key));
},).toList();
// Convert object variables to data row list
List<DataRow> dataRows = filteredPosts.map((post) {
Map<String, dynamic> postJson = jsonDecode(post.toJsonObjectString()) as Map<String, dynamic>;
List<DataCell> dataCells = columnNames.map((key){
return DataCell(
TextField(
controller: TextEditingController(text: postJson[key].toString()),
onSubmitted: (inputStr){
postJson[key] = inputStr;
// Post Data
var url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
var res = http.post(url, body: jsonEncode(postJson));
res.then((value) => print(value.body),);
},
));
}).toList();
return DataRow(cells: dataCells);
},).toList();
return SingleChildScrollView(
child: Container(
alignment: Alignment.topCenter,
child: Column(children: [
SizedBox(
width: 800,
child: searchBar,
),
SizedBox(
width: 800,
child: DataTable(columns: dataColumns, rows: dataRows),
)
]),
),
);
}
}


Leave a comment