博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
flutter顶部小部件_使用VoidCallback和Function(x)与Flutter进行小部件通信
阅读量:2508 次
发布时间:2019-05-11

本文共 5633 字,大约阅读时间需要 18 分钟。

flutter顶部小部件

In this article we’re going to investigate how we can use callback-style events to communicate between widgets with Flutter.

在本文中,我们将研究如何使用Flutter在回调控件之间使用回调风格的事件进行通信。

Why is this important? It allows us to separate our widgets into small, testable units that can be adaptable to their context.

为什么这很重要? 它使我们可以将小部件分成可测试的小单元,以适应其上下文。

创建一个新的Flutter项目 (Creating a New Flutter Project)

As always, we’ll start off by setting up a new project:

与往常一样,我们将从建立一个新项目开始:

# New Flutter project$ flutter create widget_communication# Open this up inside of VS Code$ cd widget_communication && code .

We can now open this up in the iOS or Android simulator from within VS Code.

现在,我们可以在VS Code中的iOS或Android模拟器中打开它。

算这个! (Count This!)

The first method we’re going to use is simply passing data down to the child as a property. Let’s update main.dart to contain a reference to our CounterPage that we’ll create in a second:

我们将要使用的第一种方法只是将数据作为属性传递给子级。 让我们更新main.dart以包含对我们的CounterPage的引用,该引用将在第二秒创建:

import 'package:flutter/material.dart';import 'package:widget_communication/counter_page.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget {  @override  Widget build(BuildContext context) {    return MaterialApp(      title: 'Widget Communication',      home: CounterPage(),    );  }}

The CounterPage widget is a simple StatefulWidget:

CounterPage小部件是一个简单的StatefulWidget

// counter_page.dartimport 'package:flutter/material.dart';import 'package:widget_communication/count.dart';class CounterPage extends StatefulWidget {  _CounterPageState createState() => _CounterPageState();}class _CounterPageState extends State
{ int count = 0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Widget Communication")), body: Center( child: Count(count), ), ); }}

Inside of this widget we’re establishing a count equal to 0 and passing this into a widget named Count as a property. Let’s create the Count widget:

在此小部件内部,我们将建立一个等于0count ,并将其作为属性传递给名为Count的小部件。 让我们创建Count小部件:

// count.dartimport 'package:flutter/material.dart';class Count extends StatelessWidget {  final int count;  Count(this.count);  @override  Widget build(BuildContext context) {    return Text("$count");  }}

This gives us the following expected count of 0:

这使我们获得以下预期计数0

虚空回调 (VoidCallback)

For example’s sake, let’s turn our count into a Button and say that any time we click the button we want to notify the parent CounterPage.

例如,让我们将计数变成一个Button并说,每当我们单击该按钮时,我们都希望通知父CounterPage

As we don’t want to return a value here, we’ll need to register a VoidCallback. We’ll also add braces to the items within our Count constructor to make them named parameters.

由于我们不想在此处返回值,因此需要注册VoidCallback 。 我们还将在Count构造函数中的项目上添加括号,以使其成为命名参数。

// count.dartclass Count extends StatelessWidget {  final int count;  final VoidCallback onCountSelected;  Count({@required this.count, this.onCountSelected});  @override  Widget build(BuildContext context) {    return FlatButton(      child: Text("$count"),      onPressed: () => onCountSelected(),    );  }}

We’ll then need to update our CounterPage to listen to the onCountSelected callback:

然后,我们需要更新CounterPage来监听onCountSelected回调:

// counter_page.dartWidget build(BuildContext context) {  return Scaffold(    appBar: AppBar(title: Text("Widget Communication")),    body: Center(      child: Count(        count: count,        onCountSelected: () {          print("Count was selected.");        },      ),    ),  );}

If we select the value of our counter now, we should see Count was selected. inside of the debug console!

如果现在选择计数器的值,则应该看到Count was selected. 在调试控制台内部!

功能(x) (Function(x))

Whilst the use of VoidCallback is great for identifying callback events with no expected value, what do we do when we want to return a value back to the parent?

尽管使用VoidCallback可以很好地识别没有期望值的回调事件,但是当我们想将值返回给父对象时我们该怎么办?

Enter, Function(x):

输入, Function(x)

// counter_page.dartimport 'package:flutter/material.dart';class Count extends StatelessWidget {  final int count;  final VoidCallback onCountSelected;  final Function(int) onCountChange;  Count({    @required this.count,    @required this.onCountChange,    this.onCountSelected,  });  @override  Widget build(BuildContext context) {    return Row(      mainAxisAlignment: MainAxisAlignment.center,      children: 
[ IconButton( icon: Icon(Icons.add), onPressed: () { onCountChange(1); }, ), FlatButton( child: Text("$count"), onPressed: () => onCountSelected(), ), IconButton( icon: Icon(Icons.remove), onPressed: () { onCountChange(-1); }, ), ], ); }}

Here we’ve added a couple of buttons and a new Function(int) named onCountChange that we’re calling with the value that we want to pass back to the parent.

在这里,我们添加了几个按钮和一个名为onCountChange的新Function(int) ,我们正在调用该函数,并将其值传递回父级。

Inside of the parent we’re able to listen to this and change the value of count accordingly:

在父级内部,我们可以监听此值并相应地更改count的值:

class _CounterPageState extends State
{ int count = 0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Widget Communication")), body: Center( child: Count( count: count, onCountSelected: () { print("Count was selected."); }, onCountChange: (int val) { setState(() => count += val); }, ), ), ); }}

Here’s the result of our work:

这是我们工作的结果:

翻译自:

flutter顶部小部件

转载地址:http://nihgb.baihongyu.com/

你可能感兴趣的文章
程序猿是如何解决SQLServer占CPU100%的--马非码
查看>>
Shell之sed用法 转滴
查看>>
百度ueditor 拖文件或world 里面复制粘贴图片到编辑中 上传到第三方问题
查看>>
python基础之函数参数、嵌套、返回值、对象、命名空间和作用域
查看>>
公式推导【ASRCF//CVPR2019】
查看>>
Python(4)_Python中的数据类型
查看>>
HTTP 响应头信息
查看>>
cocos2dx中的层CCLayer
查看>>
Windows XP硬盘安装Ubuntu 12.04双系统图文详解
查看>>
【资料】哈代&拉马努金相关,悼文,哈佛演讲,及各种杂七杂八资料整理
查看>>
Use weechat (IRC client) on OS X. MacBook Pro
查看>>
Luogu P3616 富金森林公园
查看>>
[Nowcoder] 六一儿童节(拼多多)
查看>>
centos6.7用yum安装redis解决办法及IP限制配置
查看>>
用DataReader 分页与几种传统的分页方法的比较
查看>>
看起来像是PS的照片,实际上却令人难以置信!
查看>>
随笔一则
查看>>
WEB 小案例 -- 网上书城(一)
查看>>
加入博客园八个月了
查看>>
怎样实现前端裁剪上传图片功能
查看>>