You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter自定义类列表无法输出内容,请求技术帮助

自定义类列表数据无法输出的问题与解决

我正在跟随The Net Ninja发布的3年前的Flutter教程学习,目前卡在自定义类部分,无法从自定义类列表中输出信息。附上我的实现代码,朋友提供的Map列表写法也未能解决问题,希望得到帮助与解释。

我的实现代码

import 'package:flutter/material.dart';
import 'quote.dart';

void main() => runApp(const MaterialApp(
  home: QuoteList(),
));

class QuoteList extends StatefulWidget {
  const QuoteList({Key? key}) : super(key: key);

  @override
  State<QuoteList> createState() => _QuoteListState();
}

class _QuoteListState extends State<QuoteList> {
  List<Quote> quotes = [
    Quote(author: 'Oscar Wilde', text: 'Be yourself; everyone else is already taken'),
    Quote(author: 'Oscar Wilde', text: 'I have nothing to declare except my genius'),
    Quote(author: 'Oscar Wilde', text: 'The truth is rarely pure and never simple')
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        title: const Text('Awesome Quotes'),
        centerTitle: true,
        backgroundColor: Colors.redAccent,
      ),
      body: ListView.builder(
        padding: const EdgeInsets.all(10.0),
        itemCount: quotes.length,
        itemBuilder: (BuildContext context, int index){
          return Center(child: Text('${quotes.author} - ${quotes.text}'));
        },
      ),
    );
  }
}

朋友提供的Map列表写法

List<Map<String, dynamic>> quote = [
{'author': 'Osc...', 'text': "aaa"},
{'author': 'Osc...', 'text': "aaa"}
];

问题根源与修复

你的核心错误是直接访问列表对象的属性:quotes是一个List<Quote>类型的列表,不是单个Quote实例,不能直接调用quotes.author或quotes.text。必须通过index索引获取列表中的单个元素,再访问其属性。

修改itemBuilder中的代码即可解决:

itemBuilder: (BuildContext context, int index){
  // 获取当前索引对应的Quote对象
  final currentQuote = quotes[index];
  return Center(child: Text('${currentQuote.author} - ${currentQuote.text}'));
},

或者直接简化为:

itemBuilder: (BuildContext context, int index){
  return Center(child: Text('${quotes[index].author} - ${quotes[index].text}'));
},

关于Map列表写法的说明

朋友提供的Map列表写法本身没问题,但你如果直接用quote.author同样会报错,因为quote是列表,不是单个Map。正确的访问方式应该是:

// 假设使用朋友的quote列表
itemBuilder: (BuildContext context, int index){
  return Center(child: Text('${quote[index]['author']} - ${quote[index]['text']}'));
},

自定义类 vs Map列表的区别

  • 自定义类(如Quote)具备类型安全性:编译时就能检查属性拼写错误,IDE也会提供代码提示,避免运行时出错。
  • Map列表灵活性高,但没有类型检查,键名拼写错误要到运行时才会暴露,维护成本更高。

内容的提问来源于stack exchange,提问作者SgtPepega

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 19:23:07