Как использовать пользовательские виджеты во флаттере - PullRequest
0 голосов
/ 14 апреля 2020

Я новичок во Флаттере и следую официальному учебнику Флаттера, чтобы изучить основы флаттера.

Итак, я хочу создать повторно используемый компонент с именем "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 говорит, что:

Метод 'CustonCard' не определен для класса 'MyApp'.

Как решить эту проблему?

Ошибка в терминале:

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

Редактировать: исправлена ​​орфографическая ошибка. Также добавляем консольный журнал.

Ответы [ 2 ]

1 голос
/ 14 апреля 2020

У вас происходит несколько ошибок, но не волнуйтесь, это происходит в самом начале. Итак, давайте разберемся с проблемами:

Во-первых, внутри тела вы определили виджет Center , который допускает в нем только одного ребенка, но вы попытались поместить два виджета ( Текст и CustomCard ). Таким образом, чтобы поместить оба виджета, вы можете изменить его на что-то вроде этого:

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

Кроме того, обратите внимание, что функция onPress принимает функцию в качестве аргумента, но вы передаете результат print (.. .) , что void . Просто измените его на:

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

Наконец, я думаю, вы пропустили определение переменной index . Просто добавьте:

String index = "card1";
1 голос
/ 14 апреля 2020

Эй, пожалуйста, проверьте обновленный код здесь. Есть пара ошибок компиляции, поскольку вы оборачиваете и Text, и ваш CustomWidget в Center, где он принимает только один дочерний виджет, а также при методе onPress требуется некоторое изменение кода.

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

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:Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text('centre'),
                  CustomCard(
                      index:'card1',
                      onPress: onPress
                  )
                ],
              )
          )
      ),
    );
  }
  onPress(index){
    print("this is $index");

  }
}
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(index);
            },
          )
        ],
      ),
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...