英文:
I want to reduce the amount of lines this file has
问题
我一直在尝试缩短这个文件中的代码行长度,但不知道该怎么做。我尝试在某些部分不重复相同的代码两次,但似乎无法将其制作成一个函数。
我想要制作成一个函数的代码是位于搜索栏和删除按钮上的代码。我尝试寻找如何将其制作成函数或其他有效方法的解决方案,但没有找到。大多数情况下,都是重写整个代码以便加入解决方案。
以下是您提供的代码的翻译:
import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:velneoapp/api/modelos/api_model_partes.dart';
import 'package:velneoapp/views/partes/detalle_de_parte.dart';
class PartesView extends StatefulWidget {
const PartesView({super.key});
@override
State<PartesView> createState() => _PartesViewState();
}
class Debouncer {
int? milliseconds;
VoidCallback? action;
Timer? timer;
run(VoidCallback action) {
if (null != timer) {
timer!.cancel();
}
timer = Timer(
const Duration(milliseconds: Duration.millisecondsPerSecond),
action,
);
}
}
class _PartesViewState extends State<PartesView> {
String string = "";
final TextEditingController _searchController = TextEditingController();
Partes? dataFromAPI;
final _debouncer = Debouncer();
bool _isLoading = true;
List<Prt> valores = [];
@override
void initState() {
_getData();
setState(() {});
super.initState();
}
_getData() async {
try {
String url =
"https://demoapi.velneo.com/verp-api/vERP_2_dat_dat/v1/vta_ped_g?page%5Bsize%5D=20&fields=id,clt,emp&api_key=api123";
http.Response res = await http.get(Uri.parse(url));
if (res.statusCode == 200) {
log("Correcto");
dataFromAPI = Partes.fromJson(json.decode(res.body));
_isLoading = false;
setState(() {});
} else {
log("${res.statusCode}");
throw ("Error durante la conexión");
}
} catch (e) {
log("Error antes de conectarse => ${e.toString()}");
}
valores = dataFromAPI!.vtaPedGs;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Partes"),
),
body: _isLoading
? const Center(
child: CircularProgressIndicator(),
)
: Column(
children: [
//Search Bar to List of typed Subject
Container(
padding: const EdgeInsets.all(15),
child: TextField(
textInputAction: TextInputAction.search,
controller: _searchController,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: const BorderSide(
color: Colors.grey,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
borderSide: const BorderSide(
color: Colors.blue,
),
),
suffixIcon: IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
_searchController.text = "";
string = _searchController.text;
},
),
contentPadding: const EdgeInsets.all(15.0),
hintText: 'Buscar...',
),
onChanged: (string) {
_debouncer.run(
() {
setState(
() {
valores = dataFromAPI!.vtaPedGs
.where(
(u) => (u.id
.toString()
.toLowerCase()
.contains(string.toLowerCase()) ||
u.clt
.toString()
.toLowerCase()
.contains(string.toLowerCase()) ||
u.emp
.toLowerCase()
.contains(string.toLowerCase())),
)
.toList();
},
);
log("valores: $valores");
},
);
},
),
),
Expanded(
child: ListView.builder(
shrinkWrap: true,
physics: const ClampingScrollPhysics(),
padding: const EdgeInsets.all(5),
itemCount: valores.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
setId(dataFromAPI!.vtaPedGs[index].id);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
const DetalleDePartesView()),
);
},
child: Card(
child: ClipPath(
clipper: ShapeBorderClipper(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(3),
),
),
child: Container(
padding: const EdgeInsets.all(4),
decoration: const BoxDecoration(
border: Border(
left:
BorderSide(color: Colors.green, width: 5),
),
),
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"ID: ${valores[index].id}",
style: const TextStyle(fontSize: 16),
),
Text(
"Cliente: ${valores[index].clt}",
style: const TextStyle(fontSize: 16),
),
Text(
"Empresa: ${valores[index].emp}",
style: const TextStyle(fontSize: 16),
),
],
),
),
),
),
),
);
},
),
),
],
),
);
}
}
正如我所说,我尝试在重复两次的代码上创建一个函数,但没有成功。
英文:
I've been trying to reduce the length of the lines of code in this file, and I don't know how. I tried not repeating the same code twice in some parts, but I can't seem to make this a function.
The code I want to make a function is the one that is on the search bar and the delete button from it, I searched for a solution on how to make it a function or something that worked, but i didn't find something. It was mostly re-writing my whole code so I can put the solution.
The code:
import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:velneoapp/api/modelos/api_model_partes.dart';
import 'package:velneoapp/views/partes/detalle_de_parte.dart';
class PartesView extends StatefulWidget {
const PartesView({super.key});
@override
State<PartesView> createState() => _PartesViewState();
}
class Debouncer {
int? milliseconds;
VoidCallback? action;
Timer? timer;
run(VoidCallback action) {
if (null != timer) {
timer!.cancel();
}
timer = Timer(
const Duration(milliseconds: Duration.millisecondsPerSecond),
action,
);
}
}
class _PartesViewState extends State<PartesView> {
String string = "";
final TextEditingController _searchController = TextEditingController();
Partes? dataFromAPI;
final _debouncer = Debouncer();
bool _isLoading = true;
List<Prt> valores = [];
@override
void initState() {
_getData();
setState(() {});
super.initState();
}
_getData() async {
try {
String url =
"https://demoapi.velneo.com/verp-api/vERP_2_dat_dat/v1/vta_ped_g?page%5Bsize%5D=20&fields=id,clt,emp&api_key=api123";
http.Response res = await http.get(Uri.parse(url));
if (res.statusCode == 200) {
log("Correcto");
dataFromAPI = Partes.fromJson(json.decode(res.body));
_isLoading = false;
setState(() {});
} else {
log("${res.statusCode}");
throw ("Error durante la conexión");
}
} catch (e) {
log("Error antes de conectarse => ${e.toString()}");
}
valores = dataFromAPI!.vtaPedGs;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Partes"),
),
body: _isLoading
? const Center(
child: CircularProgressIndicator(),
)
: Column(
children: [
//Search Bar to List of typed Subject
Container(
padding: const EdgeInsets.all(15),
child: TextField(
textInputAction: TextInputAction.search,
controller: _searchController,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: const BorderSide(
color: Colors.grey,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
borderSide: const BorderSide(
color: Colors.blue,
),
),
suffixIcon: IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
_searchController.text = "";
string = _searchController.text;
},
),
contentPadding: const EdgeInsets.all(15.0),
hintText: 'Buscar...',
),
onChanged: (string) {
_debouncer.run(
() {
setState(
() {
valores = dataFromAPI!.vtaPedGs
.where(
(u) => (u.id
.toString()
.toLowerCase()
.contains(string.toLowerCase()) ||
u.clt
.toString()
.toLowerCase()
.contains(string.toLowerCase()) ||
u.emp
.toLowerCase()
.contains(string.toLowerCase())),
)
.toList();
},
);
log("valores: $valores");
},
);
}, //toLowerCase().contains(
//string.toLowerCase(),
),
),
Expanded(
child: ListView.builder(
shrinkWrap: true,
physics: const ClampingScrollPhysics(),
padding: const EdgeInsets.all(5),
itemCount: valores.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
setId(dataFromAPI!.vtaPedGs[index].id);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
const DetalleDePartesView()),
);
},
child: Card(
child: ClipPath(
clipper: ShapeBorderClipper(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(3),
),
),
child: Container(
padding: const EdgeInsets.all(4),
decoration: const BoxDecoration(
border: Border(
left:
BorderSide(color: Colors.green, width: 5),
),
),
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"ID: ${valores[index].id}",
style: const TextStyle(fontSize: 16),
),
Text(
"Cliente: ${valores[index].clt}",
style: const TextStyle(fontSize: 16),
),
Text(
"Empresa: ${valores[index].emp}",
style: const TextStyle(fontSize: 16),
),
],
),
),
),
),
),
);
},
),
),
],
),
);
}
}
As I said, I tried to do a function on the code I repeated twice, but it didn't work
答案1
得分: 1
更改一小部分以减少一些行数的方法是将以下内容从:
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"ID: ${valores[index].id}",
style: const TextStyle(fontSize: 16),
),
Text(
"Cliente: ${valores[index].clt}",
style: const TextStyle(fontSize: 16),
),
Text(
"Empresa: ${valores[index].emp}",
style: const TextStyle(fontSize: 16),
),
],
),
更改为:
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (final text in [
"ID: ${valores[index].id}",
"Cliente: ${valores[index].clt}",
"Empresa: ${valores[index].emp}"
])
Text(
text,
style: const TextStyle(fontSize: 16),
),
],
),
英文:
one minor thing you could do to cut some lines is to change
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"ID: ${valores[index].id}",
style: const TextStyle(fontSize: 16),
),
Text(
"Cliente: ${valores[index].clt}",
style: const TextStyle(fontSize: 16),
),
Text(
"Empresa: ${valores[index].emp}",
style: const TextStyle(fontSize: 16),
),
],
),
to
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (final text in [
"ID: ${valores[index].id}",
"Cliente: ${valores[index].clt}",
"Empresa: ${valores[index].emp}"
])
Text(
text,
style: const TextStyle(fontSize: 16),
),
],
),
答案2
得分: 0
不需要编写代码,只需使用现有的代码片段并创建其功能,如果需要,传递一些值。
例如,这是用于搜索文本字段的代码:
Widget searchField(){
return TextField(
textInputAction: TextInputAction.search,
controller: _searchController,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: const BorderSide(
color: Colors.grey,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
borderSide: const BorderSide(
color: Colors.blue,
),
),
suffixIcon: IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
_searchController.text = "";
string = _searchController.text;
},
),
contentPadding: const EdgeInsets.all(15.0),
hintText: 'Buscar...',
),
onChanged: (string) {
_debouncer.run(
() {
setState(
() {
valores = dataFromAPI!.vtaPedGs
.where(
(u) => (u.id
.toString()
.toLowerCase()
.contains(string.toLowerCase()) ||
u.clt
.toString()
.toLowerCase()
.contains(string.toLowerCase()) ||
u.emp
.toLowerCase()
.contains(string.toLowerCase())),
)
.toList();
},
);
log("valores: $valores");
},
);
},
);
}
就像最后三个Text小部件一样,它们具有相同的样式,只是值不同:
Widget myText(String text) {
return Text(
text,
style: const TextStyle(fontSize: 16),
);
}
然后通过将文本传递给它来调用它,例如:myText("ID: ${valores[index].id}")
和 myText("Cliente: ${valores[index].id}")
。
至于你的用例,我不清楚为什么在Card内部有一个ClipPath内部还有一个Container,我知道你想要装饰和设计,但所有这些都可以使用Container小部件实现,探索一下不同的小部件吧!
希望这对你有帮助。
英文:
You don't need to write the code you can just take the come code snippet and make it's function, pass some values if there's some requirements is there.
Like here's the code for your search textField:
Widget searchField(){
return TextField(
textInputAction: TextInputAction.search,
controller: _searchController,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(25.0),
borderSide: const BorderSide(
color: Colors.grey,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(20.0),
borderSide: const BorderSide(
color: Colors.blue,
),
),
suffixIcon: IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
_searchController.text = "";
string = _searchController.text;
},
),
contentPadding: const EdgeInsets.all(15.0),
hintText: 'Buscar...',
),
onChanged: (string) {
_debouncer.run(
() {
setState(
() {
valores = dataFromAPI!.vtaPedGs
.where(
(u) => (u.id
.toString()
.toLowerCase()
.contains(string.toLowerCase()) ||
u.clt
.toString()
.toLowerCase()
.contains(string.toLowerCase()) ||
u.emp
.toLowerCase()
.contains(string.toLowerCase())),
)
.toList();
},
);
log("valores: $valores");
},
);
}, //toLowerCase().contains(
//string.toLowerCase(),
);
}
Just like the last three Text widgets that has the same style just different values:
Widget myText(String text) {
return Text(
text,
style: const TextStyle(fontSize: 16),
);
}
and call it with passing your text to display myText("ID: ${valores[index].id}")
and myText("Cliente: ${valores[index].id}")
.
And i don't know about your use-case but why is there Container inside a ClipPath inside a Card, i know you want the decoration and designing but all that can be possible with the Container widget, Explore widgets..!
Hope this'll help you...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论