简体   繁体   中英

How to use Custom Widgets in flutter

I am new to Flutter and I am following Flutter's official tutorial to learn basics of flutter.

So, I want to create a reusable component named "CustomCard" and I did this:

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,
                  )
             ],
          ),
      );
   }
}

Now, to use it in MyApp, I did this:

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')
                    ),
                ),
            ),
        );
       }
      }

Now my IDE says that:

The method 'CustonCard' isn't defined for the class 'MyApp'.

How to solve this?

Error in terminal:

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

Edit: corrected a spelling mistake. Also adding console log.

Hey Please check the updated code here. There are couple of compile errors as you are wrapping up both Text and you CustomWidget in Center where it accepts only one child widget and also at the onPress method some code change required.

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);
            },
          )
        ],
      ),
    );
  }
}

You have got a few mistakes going on, but don't worry it happens at the very beginning. So let's step into the problems:

First, inside the body you've defined a Center Widget which only allows a single child within it but you have tried to put two Widgets ( Text and CustomCard ). So to put both widgets you could change it to something like this:

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

Moreover, pay attention that the onPress function takes a Function as argument but you are passing the result of print(...) which is void . Simply change it to:

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

Finally, I think you missed to define the index variable. Simply add:

String index = "card1";
                  child: Center(
                child: Row(
                  children: <Widget>[
                    _box(), //Custom pin view
                    _box(), //Custom pin view
                    _box(), //Custom pin view
                    _box(),//Custom pin view
                  ],
                ),
              )

and Custom Widgets (_box) Code

Widget _box() {
return Container(
margin: EdgeInsets.symmetric(vertical: 5, horizontal: 3),
alignment: Alignment.center,
height: 50,
width: 50,
child: TextField(
  keyboardType: TextInputType.number,
  maxLength: 1,
  decoration: InputDecoration(border: InputBorder.none, counterText: ''),
),
decoration: BoxDecoration(border: Border.all(color: Colors.blue)),

); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM