我试图理解状态是如何与Flutter一起工作的,我有一个子部件需要在父部件中更改一些内容。我可以使用打印检测子部件中按钮的按下。但是当我试图将此更改冒泡到父部件时,它没有捕捉到它。
我已经通过了一些教程,我不是100%肯定我了解状态如何工作或应该工作,我想我在这里错过了一些东西。
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
//Consider this function as your _onNotification and important to note I am using setState() within :)
void _incrementCounter() {
print("pressed"); // Does not detect pressed.
setState(() {
_counter++; // counter is not increased
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
widget.title,
style: TextStyle(color: Colors.white),
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button $_counter times:',
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
),
],
),
),
floatingActionButton: MyFloatButton(
_incrementCounter), //Pass delegate to _incrementCounter method
);
}
}
class MyFloatButton extends StatefulWidget {
// Here I am receiving the function in constructor as params
const MyFloatButton(this.onPressedFunction, {super.key});
// Should be the delegated function from _MyHomePageState
final Function onPressedFunction;
@override
_MyFloatButtonState createState() => new _MyFloatButtonState();
}
class _MyFloatButtonState extends State<MyFloatButton> {
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(5.0),
decoration: BoxDecoration(
color: Colors.orangeAccent,
borderRadius: new BorderRadius.circular(50.0)),
child: IconButton(
icon: Icon(Icons.add),
color: Colors.white,
onPressed: () => {
//print('pressed') // Does work shows button pressed
widget.onPressedFunction
}, // call the delegated method to detect the pressed
),
);
}
}
尝试的事情:
onPressed: widget.onPressedFunction()
结果
生成期间调用了setState()或NeedmarksBuild
onPressed: widget.onPressedFunction
结果
参数类型“Function”不能分配给参数类型“void Function()?”。
onPressed: () => widget.onPressedFunction,
结果
不改变什么也做不了
3条答案
按热度按时间kr98yfug1#
请尝试这个。onPressedFunction是一个函数,因此声明如下函数。
i1icjdpr2#
在MyFloatButton中,您将在函数中调用函数
它应该如下所示
ccgok5k53#
改变这个
到这个
只需删除大括号并在此处添加()即可