flutter - 我如何从按下的浮动按钮调用一个类
问题描述
我一直在尝试使用浮动操作按钮来执行课程,但我一直在尝试一切并失败了。这是我的代码:
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
return runApp(
MaterialApp(
home: Scaffold(
backgroundColor: Colors.white70,
appBar: AppBar(
centerTitle: true,
title: Text('Dices'),
backgroundColor: Colors.teal,
),
body: DicePage(),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add), onPressed: () {}),
),
),
);
}
class DicePage extends StatefulWidget {
@override
_DicePageState createState() => _DicePageState();
}
class _DicePageState extends State<DicePage> {
int leftDiceNum = 1;
int rightDiceNum = 1;
void diceRandomizer() {
setState(() {
leftDiceNum = Random().nextInt(6) + 1;
rightDiceNum = Random().nextInt(6) + 1;
});
}
@override
Widget build(BuildContext context) {
return Center(
child: Row(
children: <Widget>[
Expanded(
child: FlatButton(
onPressed: () {
diceRandomizer();
},
child: Image.asset('images/dice$leftDiceNum.png'),
),
),
Expanded(
child: FlatButton(
onPressed: () {
diceRandomizer();
},
child: Image.asset('images/dice$rightDiceNum.png'),
),
),
],
),
);
}
}
现在代码是一个简单的骰子应用程序,如果我按下图像,DiceRandomizer 功能就会激活,它会随机给出一个 1..6 的数字。然后图像被呈现。但我想用浮动操作按钮做到这一点。
解决方案
据我所知,这是因为该类未定义,并尝试修复您的代码
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
return runApp(
MaterialApp(home: DicePage()),
);
}
class DicePage extends StatefulWidget {
@override
_DicePageState createState() => _DicePageState();
}
class _DicePageState extends State<DicePage> {
int leftDiceNum = 1;
int rightDiceNum = 1;
diceRandomizer() {
setState(() {
leftDiceNum = Random().nextInt(6) + 1;
rightDiceNum = Random().nextInt(6) + 1;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white70,
appBar: AppBar(
centerTitle: true,
title: Text('Dices'),
backgroundColor: Colors.teal),
body: Center(
child: Row(
children: <Widget>[
Expanded(
child: TextButton(
onPressed: () {
diceRandomizer();
},
child: Image.asset('images/dice$leftDiceNum.png'),
),
),
Expanded(
child: TextButton(
onPressed: () {
diceRandomizer();
},
child: Image.asset('images/dice$rightDiceNum.png'),
),
),
],
),
),
floatingActionButton: Row(
children: [
FloatingActionButton(
onPressed: () {diceRandomizer();},
),
FloatingActionButton(
onPressed: (){diceRandomizer();},
)
],
),
);
}
}
笔记
- 我制作了 2 个 FloatingActionButton
- FlatButton 已弃用,必须迁移到 TextButton
试试看结果,如果有错误你可以评论,我会帮助你。
推荐阅读
- c++ - cv::Mat::split(args) 的正确参数
- php - 我可以在 Laravel 中使用 php deployer 进行 CI/CD 吗?
- java - 当您从任务栏关闭 javafx 应用程序时会触发什么事件以及如何处理它?
- python - 在 matplotlib 中绘图时如何隐藏文本
- java - JPA OneToOne 映射的 AngularJs $http Post Requst 返回字符串而不是 JSON 数据
- reactjs - React Formik onSubmit Async 调用了两次
- javascript - 递归语句,遍历嵌套对象/数组 - 但是它怎么知道这样做呢?(JS算法)
- docker - 这个命令有什么问题 - docker volume 命令
- javascript - 被 CORS 政策阻止的 Firebase 函数 api
- android - 这些声明之间有什么区别 - Kotlin