Mai*_*oqi 1 sorting listview flutter
我正在制作一个关于 flutter 的应用程序,其中产品列表中的价格等项目必须按升序排列。在互联网上搜索后,我想出了使用compareTo和sort函数的解决方案,但不幸的是,我在sort()上遇到错误,即:这里的表达式的类型为void,因此无法使用。完整的正确代码位于Github上https://github.com/MaidaFarooqi9/Application/blob/master/lib/ProductScreen.dart 我试图修改的代码部分是
return Container(
child:ListView.separated(
itemBuilder: (context, index){
return ListTile(
title:Text(products[index].name),
leading:products[index].i,
subtitle:Column(
children:<Widget>[
if (!ProductScreen.name) Text("\$${products[index].price}",
style: TextStyle(color: Colors.redAccent, fontSize: 20, fontWeight: FontWeight.w500),)
else
Text(products.sort((a,b)=>a.price.compareTo(b.price))) ,
Run Code Online (Sandbox Code Playgroud)
if-else 条件在 if() 处显示未排序的列表,否则价格将按升序排列
只需查看我根据您给定的示例代码创建的示例:
import 'package:flutter/material.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(child: SampleApp()),
),
);
}
}
class SampleApp extends StatefulWidget {
SampleApp({Key key}) : super(key: key);
@override
_SampleAppState createState() => _SampleAppState();
}
class _SampleAppState extends State<SampleApp> {
var products = [
Product("sample", 12),
Product("name", 50),
Product("azpc", 78),
Product("hplm", 3),
Product('ampl', 2),
];
@override
void initState() {
// TODO: implement initState
super.initState();
products.sort((a, b) => a.price.compareTo(b.price));
}
@override
Widget build(BuildContext context) {
return Container(
child: ListView.separated(
itemBuilder: (context, index) {
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(products[index].name),
Text(products[index].price.toString()),
],
),
),
);
},
separatorBuilder: (context, int) => Divider(),
itemCount: products.length),
);
}
}
class Product {
final String name;
final double price;
Product(this.name, this.price);
}
Run Code Online (Sandbox Code Playgroud)
让我知道它是否有效。