簡體   English   中英

在 Flutter 中創建自定義小部件

[英]Creating a Custom widget in Flutter

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

int _weight =60;

class RoundIconData extends StatefulWidget {

@override
_RoundIconDataState createState() => _RoundIconDataState();
}
class _RoundIconDataState extends State<RoundIconData> {

RoundIconData({@required this.icon,@required this.pressme});
final IconData icon;
final int pressme;

@override
Widget build(BuildContext context) {
 return RawMaterialButton(
   child: Icon(icon),
   onPressed: (){
    setState(() {
      if(icon == FontAwesomeIcons.minus){
        _weight--;
      }
      else{
        _weight++
      }
    });
  },
  elevation: 6.0,
  constraints: BoxConstraints.tightFor(
    width: 56.0,
    height: 56.0,
  ),
  shape: CircleBorder(),
  fillColor: Color(0xFF4C4F5E),
);
}
}

我在創建這個時遇到錯誤。

我想要的是

帶有 RawmaterialButton 的自定義小部件,我可以通過它添加圖標。 如果我添加 icon.minus 那么我給定的私有權重要減少,否則給定私有權重要增加

您可以在下面復制粘貼運行完整代碼
您必須將以下代碼移動到RoundIconData

RoundIconData({@required this.icon,@required this.pressme});
final IconData icon;
final int pressme;

並通過回調進行刷新

工作演示

在此處輸入圖像描述

完整代碼

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.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: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

int weight = 60;

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  refresh() {
    setState(() {});
  }

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RoundIconData(
              icon: Icon(FontAwesomeIcons.minus),
              notifyParent: refresh,
            ),
            RoundIconData(
              icon: Icon(Icons.add),
              notifyParent: refresh,
            ),
            Text(
              '${weight}',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class RoundIconData extends StatefulWidget {
  final Icon icon;
  final int pressme;
  final Function() notifyParent;

  RoundIconData(
      {@required this.icon,
      @required this.pressme,
      @required this.notifyParent});
  @override
  _RoundIconDataState createState() => _RoundIconDataState();
}

class _RoundIconDataState extends State<RoundIconData> {
  @override
  Widget build(BuildContext context) {
    return RawMaterialButton(
      child: widget.icon,
      onPressed: () {
        print(widget.icon.toString());
        print(Icon(FontAwesomeIcons.minus).toString());
        if (widget.icon.toString() == Icon(FontAwesomeIcons.minus).toString()) {
          weight--;
          widget.notifyParent();
          print(weight);
        } else {
          weight++;
          widget.notifyParent();
          print(weight);
        }
      },
      elevation: 6.0,
      constraints: BoxConstraints.tightFor(
        width: 56.0,
        height: 56.0,
      ),
      shape: CircleBorder(),
      fillColor: Color(0xFF4C4F5E),
    );
  }
}

通過組合較小的小部件(而不是擴展它們)來構建自定義小部件。 它有點類似於在 Android 中實現自定義ViewGroup ,其中所有構建塊都已經存在,但您提供不同的行為 - 例如,自定義布局邏輯。

構建一個在構造函數中帶有標簽的 CustomButton? 創建一個CustomButton ,它組合一個帶有標簽的ElevatedButton ,而不是通過擴展ElevatedButton

class CustomButton extends StatelessWidget {
  final String label;

  CustomButton(this.label);

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(onPressed: () {}, child: Text(label));
  }
}

然后使用CustomButton ,就像使用任何其他 Flutter 小部件一樣:

@override
Widget build(BuildContext context) {
  return Center(
    child: CustomButton("Hello"),
  );
}

在 Flutter 中創建自定義小部件

 import 'package:flutter/material.dart';
    
    
    class WelcomePage extends StatelessWidget {
      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Flutter Auth',
          theme: ThemeData(
            primaryColor: Colors.purple,
            scaffoldBackgroundColor: Colors.white,
          ),
          home:Scaffold(
            body: Center(
              child: SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      "WELCOME TO XYZ",
                      style: TextStyle(fontWeight: FontWeight.bold,color: Colors.purple,fontSize: 25),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(right: 40),
                      child: Image.asset(
                        "assets/images/food_order.png",
                        height: 200,
                      ),
                    ),
                    SizedBox(height: 10 ),
                    loginMethod(),
                    signUpMethod(),
                  ],
              ),
            ),
            ),
          ),
        );
      }
    
      // Login Button Method Widget
      Widget loginMethod(){
        return Container(
          margin: EdgeInsets.symmetric(vertical: 10),
          width: 200,
          height: 50,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(29),
            child: FlatButton(
              padding: EdgeInsets.symmetric(vertical: 10, horizontal: 40),
              color: Colors.blue,
              onPressed: (){},
              child: Text(
                'Login',
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
        );
      }
    
      // Signup button method widget
      Widget signUpMethod (){
        return Container(
          margin: EdgeInsets.symmetric(vertical: 10),
          width: 200,
          height: 50,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(29),
            child: FlatButton(
              padding: EdgeInsets.symmetric(vertical: 10, horizontal: 40),
              color: Colors.blue,
              onPressed: (){},
              child: Text(
                'Sign up',
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
        );
      }
    
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM