【发布时间】:2021-11-10 22:27:14
【问题描述】:
我正在尝试从对象列表构建卡片小部件。我在最底部的最后一个 Text(grabItem.title) 返回 Error: Not a constant expression
import 'package:flutter/material.dart';
//ItemData used in addnew.dart
class ItemData {
final String id;
final String score;
final String title;
final String description;
ItemData({
required this.id,
required this.score,
required this.title,
required this.description});
//@override
//String toString() => '{ID: $id, Score: $score, Title: $title, Description: $description}';
}
//Dummy list of items
final itemList = [
ItemData(
id: 'one',
score: '30',
title: 'Title One',
description: 'mock description'),
ItemData(
id: 'two',
score: '10',
title: 'Title Two',
description: 'mock description'),
ItemData(
id: 'three',
score: '20',
title: 'Title Three',
description: 'mock description'),
];
class ListPage extends StatelessWidget {
const ListPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text('List View',
style: TextStyle(
letterSpacing: 2.0,
),
),
centerTitle: true,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Center(
child: Listcard(),
),
], //childern
),
);
}
}
sortList(){
//itemList.sort((item1, item2)=> item2.score.compareTo(item1.score));
}
class Listcard extends StatefulWidget {
const Listcard({Key? key}) : super(key: key);
@override
_ListcardState createState() => _ListcardState();
}
class _ListcardState extends State<Listcard> {
@override
Widget build(BuildContext context) {
sortList();
var grabItem = itemList[0]; //grab the given instance to use as a list of elements
print(grabItem.title);
return
Card(
child: InkWell(
splashColor: Colors.blue.withAlpha(30),
onLongPress: (){
//print(cardTitle);
},
child: const SizedBox(
width: 300,
height: 100,
child: Text(grabItem.title),
),
),
);
}
}
最终我想为这些卡片中的每一个创建一个实例(为每个列表对象),这样我就可以在脚手架上看到我的所有项目。我对 OOP 很陌生,所以我可能会以一种非常低效的方式来解决这个问题。
【问题讨论】: