Flutter报错:‘MyHomePage’未定义‘Transaction’,求文档及结构变更信息
问题:Flutter中使用Transaction报错“The method 'Transaction' isn't defined for the type 'MyHomePage'”
跟随2022年Maximilian Schwarzmüller的Flutter教程开发,使用Transaction时出现上述错误,查阅官方文档无收获,疑惑是否是Flutter更新导致结构名称变更,附上代码如下:
import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter App', home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { final List<Transaction> transactions = [ Transaction( id: 't1', Title: 'Weekly Shoes', amount: 69.99, date: DateTime.now(), ), Transaction( id: 't2', Title: 'Weekly Groceries', amount: 16.53, date: DateTime.now(), ), ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Flutter App'), ), body: Column( children: <Widget>[ Container( width: double.infinity, child: Card( color: Colors.blue, child: Text('Chart!'), elevation: 5, ), ), Card( child: Text('List of TX!'), ), ], ), ); } }
是否使用了旧结构?
解答
这个错误和Flutter版本更新无关,Transaction不是Flutter框架自带的API,是教程里Max自定义的业务类,你漏写了这个类的定义,导致编译器无法识别它。
只需在代码中添加Transaction类的定义即可,同时修正原代码中属性名大小写不匹配的问题:
import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart'; // 新增自定义Transaction类 class Transaction { final String id; final String title; final double amount; final DateTime date; Transaction({ required this.id, required this.title, required this.amount, required this.date, }); } void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter App', home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { final List<Transaction> transactions = [ Transaction( id: 't1', title: 'Weekly Shoes', // 修正属性名大小写,和类定义保持一致 amount: 69.99, date: DateTime.now(), ), Transaction( id: 't2', title: 'Weekly Groceries', // 同步修正属性名 amount: 16.53, date: DateTime.now(), ), ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Flutter App'), ), body: Column( children: <Widget>[ Container( width: double.infinity, child: Card( color: Colors.blue, child: Text('Chart!'), elevation: 5, ), ), Card( child: Text('List of TX!'), ), ], ), ); } }
教程里肯定有这个自定义类的讲解部分,你可能遗漏了这一步,不存在Flutter结构名称变更的情况。
内容的提问来源于stack exchange,提问作者Rezam
相关产品推荐
相关产品推荐

