首页 > 解决方案 > 如何在颤振中使用自定义小部件

问题描述

我是 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 })

编辑:更正了拼写错误。还添加控制台日志。

标签: flutterdartflutter-layout

解决方案


你有一些错误正在发生,但不要担心它在一开始就会发生。那么让我们进入问题:

首先,在正文中,您定义了一个Center Widget,它只允许在其中包含一个孩子,但您尝试放置两个 Widget(TextCustomCard)。因此,要放置两个小部件,您可以将其更改为以下内容:

Center(
      child: Column(
        children: <Widget>[
          Text('centre'),
          CustomCard(...)
        ],
      ),
    ),

此外,请注意 onPress 函数将 Function 作为参数,但您传递的是print(...)的结果,它是void。只需将其更改为:

CustomCard(index: index, onPress: () => print(' this is $index'))

最后,我认为您错过了定义索引变量。只需添加:

String index = "card1";

推荐阅读