flutter - 如何在颤振中使用自定义小部件
问题描述
我是 Flutter 的新手,我正在关注 Flutter 的官方教程来学习 Flutter 的基础知识。
所以,我想创建一个名为“CustomCard”的可重用组件,我这样做了:
class CustomCard extends StatelessWidget {
CustomCard({@required this.index, @required this.onPress});
final index;
final Function onPress;
@override
Widget build(BuildContext context) {
return Card(
child: Column(
children: <Widget>[
Text('Card $index'),
FlatButton(
child: const Text('Press'),
onPressed: this.onPress,
)
],
),
);
}
}
现在,为了在 MyApp 中使用它,我这样做了:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to flutter',
home: Scaffold(
appBar: AppBar(
title: Text('hello'),
),
body: Center(
child: Text('centre'),
CustomCard(
index:'card1',
onPress: print(' this is $index')
),
),
),
);
}
}
现在我的 IDE 说:
没有为类“MyApp”定义方法“CustonCard”。
如何解决这个问题?
终端错误:
Compiler message:
lib/main.dart:17:6: Error: Place positional arguments before named arguments.
Try moving the positional argument before the named arguments, or add a name to the argument.
CustomCard(
^^^^^^^^^^
lib/main.dart:17:6: Error: Expected named argument.
CustomCard(
^
lib/main.dart:15:21: Error: No named parameter with the name '#1'.
body: Center(
^^...
/C:/src/flutter/packages/flutter/lib/src/widgets/basic.dart:1863:9: Context: Found this candidate, but the arguments don't match.
const Center({ Key key, double widthFactor, double heightFactor, Widget child })
编辑:更正了拼写错误。还添加控制台日志。
解决方案
你有一些错误正在发生,但不要担心它在一开始就会发生。那么让我们进入问题:
首先,在正文中,您定义了一个Center Widget,它只允许在其中包含一个孩子,但您尝试放置两个 Widget(Text和CustomCard)。因此,要放置两个小部件,您可以将其更改为以下内容:
Center(
child: Column(
children: <Widget>[
Text('centre'),
CustomCard(...)
],
),
),
此外,请注意 onPress 函数将 Function 作为参数,但您传递的是print(...)的结果,它是void。只需将其更改为:
CustomCard(index: index, onPress: () => print(' this is $index'))
最后,我认为您错过了定义索引变量。只需添加:
String index = "card1";
推荐阅读
- function - 如何自引用一个函数?
- wordpress - 如何在 WordPress Rest Api 中为用户正确添加自定义字段?
- javascript - 如何设置samesite=none
- c# - 在 C# 中使用 High chart mvc 创建动态图表
- git - 如何将 org 文件置于 git 控制下,以便 git 忽略计算结果部分的更改?
- google-chrome - 仅限 Safari:拒绝连接到 ... 因为它没有出现在内容安全策略的 connect-src 指令中
- javascript - 如何使用 JavaScript 制作 html 文件
- javascript - 我正在使用 discord.js 编写一个不和谐的机器人,我正在研究一个建议命令
- google-drive-api - 将大量 Google Drive 文件转移到另一个 Drive 帐户?
- qt - QT:找不到静态链接库