如何在扑扑中执行VoidCallback

时间:2018-12-22 08:53:28

标签: dart flutter

我试图测试VoidCallback,所以我创建了一个主文件,该文件具有从小部件中的平面按钮调用的功能,该功能位于单独的文件中,但不起作用。

main.dart

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Retrieve Text Input',
      home: MyCustomForm(),
    );
  }
}

// Define a Custom Form Widget
class MyCustomForm extends StatefulWidget {
  @override
  _MyCustomFormState createState() => _MyCustomFormState();
}

class _MyCustomFormState extends State<MyCustomForm> {
  final myController = TextEditingController();

  @override
  void initState() {
    super.initState();

    myController.addListener(_printLatestValue);
  }

  _printLatestValue() {
    print("Second text field: ${myController.text}");
  }

  _test() {
    print("hi there");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Retrieve Text Input'),
      ),
      body: Con(_test, myController)
    );
  }
}

controller_test.dart

import 'package:flutter/material.dart';

class Con extends StatelessWidget {
  Con(this.clickCallback, this.tc);
  final TextEditingController tc;
  final VoidCallback clickCallback;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        children: <Widget>[
          TextField(
            onChanged: (text) {
              print("First text field: $text");
            },
          ),
          TextField(
            controller: tc,
          ),
          FlatButton(
            onPressed: () => clickCallback,
            child: Text("click me"),
          )
        ],
      ),
    );
  }
}

当我单击窗口小部件中的FlatButton时,什么也没有发生,我希望打印hi there

4 个答案:

答案 0 :(得分:1)

我刚刚在另一个答案here中找到了它  我错过了(),因此正确的呼叫是:

n_nodes = 5
d = nx.gnp_random_graph(n_nodes, 0.5, directed=True)

degree_prestige = dict((v,len(d.in_edges(v))/(n_nodes-1)) for v in d.nodes())
print("DEGREE PRESTIGE :\n")

for i in degree_prestige:
    print(i, " : ", degree_prestige[i])

distance = []

temp_dis = 0
n = 0
for dest in d.nodes:
    temp_dis = 0
    n = 0
    for src in d.nodes:
        if (nx.has_path(d,src,dest) == True):
            temp_dis = temp_dis + nx.shortest_path_length(d,source = src,target = dest)
            n = n + 1
    if temp_dis == 0:
        distance.append([dest, 0])
    else:
        distance.append([dest, temp_dis/(n - 1)])
print("\nPROXIMITY PRESTIGE :\n")
for i in distance:
    print(str(i[0]) + " : " + str(i[1]))

prominance = np.random.randint(1, 4, size=n_nodes)
print("\nASSUME PROMINANCE :\n")
print(prominance)
rank_prestige = np.zeros([n_nodes], dtype = int)

path_matrix = np.zeros([n_nodes, n_nodes], dtype = int)
i = 0
j = 0
for src in d.nodes:
    for dest in d.nodes:
        if d.has_edge(dest, src):
            path_matrix[i][j] = 1
        j = j+1
    j = 0
    i = i+1
for i in range(n_nodes):
    pr_i = 0
    for j in range(n_nodes):
        pr_i = pr_i + path_matrix[i][j] * prominance[j]
    rank_prestige[i] = pr_i

print("\nRANK PRESTIGE :\n")
print(rank_prestige)

答案 1 :(得分:1)

这里有两个选择。

  1. onPressed: () => fun()就像onPressed参数是调用fun的匿名方法。

  2. onPressed: fun就像onPressed参数很有趣。

答案 2 :(得分:0)

在您的回调中,如果任何变量发生变化,请确保调用 setState。我在我的提供者中重新填充一个列表,然后使用将该列表分配给我转换为卡片列表的变量列表。变量列表需要刷新状态才能看到。

答案 3 :(得分:0)

您可以使用 Voidcallback 类从无状态小部件回调到当前页面。

只需在当前页面中添加这个自定义小部件(widget.build() 函数)

DefaultButton(
        buttonText: Constants.LOGIN_BUTTON_TEXT,
        onPressed: () => validateInputFields(),
        size: size,
      );

我的自定义小部件类是

class DefaultButton extends StatelessWidget {

  DefaultButton({this.buttonText, this.onPressed, this.size});

  final String buttonText;
  final VoidCallback onPressed;
  final Size size;

  @override
  Widget build(BuildContext context) {
    return MaterialButton(
      minWidth: size.width,
      onPressed: () => onPressed(), //callback to refered page
      padding: EdgeInsets.all(0.0),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(DEFAULT_BORDER_RADIUS),
      ),
      child: Ink(
        width: size.width,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
            colors: <Color>[
              SECONDARY_COLOR_SHADE_LITE,
              SECONDARY_COLOR_SHADE_DARK,
            ],
          ),
          borderRadius: BorderRadius.circular(DEFAULT_BORDER_RADIUS),
        ),
        child: Padding(
            padding: EdgeInsets.only(left: 20, right: 20, top: 12, bottom: 12),
            child: Text(
              buttonText,
              style: Theme.of(context).textTheme.button,
              textAlign: TextAlign.center,
            )),
      ),
    );
  }
}