[flutter] 플러터 GridView에서 아이템을 오름차순 또는 내림차순으로 정렬하는 방법은?
먼저, 정렬 기능을 구현하기 위해 GridView에 들어갈 데이터를 가지고 있는 리스트를 준비해야 합니다. 이 리스트를 기반으로 정렬된 결과를 보여주는 GridView를 구성할 것입니다.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyGridView(),
);
}
}
class MyGridView extends StatefulWidget {
@override
_MyGridViewState createState() => _MyGridViewState();
}
class _MyGridViewState extends State<MyGridView> {
List<String> items = ['Apple', 'Banana', 'Cherry', 'Date', 'Fig', 'Grape'];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Sorted GridView'),
),
body: Column(
children: <Widget>[
RaisedButton(
onPressed: () {
setState(() {
items.sort();
});
},
child: Text('Sort Ascending'),
),
RaisedButton(
onPressed: () {
setState(() {
items.sort((a, b) => b.compareTo(a));
});
},
child: Text('Sort Descending'),
),
Expanded(
child: GridView.count(
crossAxisCount: 2,
children: List.generate(items.length, (index) {
return Center(
child: Text(
items[index],
style: TextStyle(fontSize: 24.0),
),
);
}),
),
),
],
),
);
}
}
위 코드는 오름차순과 내림차순으로 아이템을 정렬하여 GridView에 표시하는 간단한 예제입니다. RaisedButton 위젯을 통해 오름차순과 내림차순 버튼이 제공되며, 해당 버튼을 누를 때마다 setState 함수를 호출하여 아이템을 재정렬하고 화면을 다시 그리게 됩니다.
이 예제를 참고하여 플러터의 GridView에서 아이템을 정렬하는 기능을 구현해 보시기 바랍니다.