Flutter Dart setState o callBack tra istanze di classi diverse

huangapple go评论77阅读模式
英文:

Flutter Dart setState o callBack tra istanze di classi diverse

问题

I'm structuring an app on 2 columns. In the left column, I would like to insert a button that updates the contents of the right column. Although keeping all the code in a single class, I can do what I have in mind. However, by creating 2 classes (one for the left column and one for the right one), I do not understand how to call the callback or setState.

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 layout demo',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  HomePageState createState() => HomePageState();
}

class HomePageState extends State<HomePage> {
  String TestoADestra = 'InitialTextOnTheRight';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter layout demo',
      home: Scaffold(
        body: Row(
          children: [
            LeftColumn(),
            RightColumn(TestoCheVorreiComparisse: TestoADestra, callbackFunction: (varTestoSostitutivo) {
              setState(() {
                TestoADestra = varTestoSostitutivo;
              });
            }),
          ],
        ),
      ),
    );
  }
}

class RightColumn extends StatefulWidget {
  final String TestoCheVorreiComparisse;
  final Function callbackFunction;

  const RightColumn({Key? key, required this.TestoCheVorreiComparisse, required this.callbackFunction})
      : super(key: key);

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

class RightColumnState extends State<RightColumn> {
  @override
  Widget build(BuildContext context) {
    return Expanded(
      flex: 4,
      child: Container(
        decoration: const BoxDecoration(
          color: Colors.blue,
        ),
        child: Column(
          children: [
            Expanded(
              child: Center(
                child: Text(widget.TestoCheVorreiComparisse),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class LeftColumn extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Expanded(
      flex: 1,
      child: Container(
        decoration: BoxDecoration(
          color: Colors.red,
        ),
        child: Column(
          children: [
            Expanded(
              child: Center(
                child: ButtonA(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class ButtonA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return TextButton(
      style: ButtonStyle(
        foregroundColor: MaterialStateProperty.all<Color>(Color.fromARGB(255, 72, 3, 201)),
      ),
      onPressed: () {},
      child: Text('Press here'),
    );
  }
}

I tried to insert:

  • regarding "ButtonA," the callback function to onPressed and I declared the function before the override something like:
final String TestoCheVorreiComparisse;
final Function callbackFunction;

const ButtonA({Key? key, required this.TestoCheVorreiComparisse, required this.callbackFunction}) : super(key: key);
  • as for "RightColumn," before the override, something like this:
String TestoCheVorreiComparisse = "Let's see if it works";
callback(varTestoSostitutivo) {
  setState(() {
    TestoCheVorreiComparisse = varTestoSostitutivo;
  });
}

I am told, and I understand why, that there is no callback function in "ButtonA." How can I do this? Thank you!

英文:

Good evening everyone.

I'm structuring an app on 2 columns. In the left column I would like to insert a button that updates the contents of the right column. Although keeping all the code in a single class I can do what I have in mind, creating 2 classes (one for the left column and one for the right one) I do not understand how to call the callback or setState.

import &#39;package:flutter/material.dart&#39;;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: &#39;Flutter layout demo&#39;,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
HomePageState createState() =&gt; HomePageState();
}
class HomePageState extends State&lt;HomePage&gt; {
String TestoADestra = &#39;TestoInizialeADestra&#39;;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: &#39;Flutter layout demo&#39;,
home: Scaffold(
body: Row(
children: [
ColonnaSx(),
ColonnaDx(),
],
)),
);
}
}
class ColonnaDx extends StatefulWidget {
@override
ColonnaDxState createState() =&gt; ColonnaDxState();
}
class ColonnaDxState extends State&lt;ColonnaDx&gt; {
@override
Widget build(BuildContext context) {
return Expanded(
flex: 4,
child: Container(
decoration: const BoxDecoration(
color: Colors.blue,
),
child: Column(
children: [
Expanded(
child: Center(
child: Text(
&#39;Here I would like to put other things but for the moment there is this&#39;),
),
),
],
),
),
);
}
}
class ColonnaSx extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Expanded(
flex: 1,
child: Container(
decoration: BoxDecoration(
color: Colors.red,
),
child: Column(
children: [
Expanded(
child: Center(
child: BottoneA(),
),
),
],
),
),
);
}
}
class BottoneA extends StatelessWidget {
@override
Widget build(BuildContext context) {
return TextButton(
style: ButtonStyle(
foregroundColor:
MaterialStateProperty.all&lt;Color&gt;(Color.fromARGB(255, 72, 3, 201)),
),
onPressed: () {},
child: Text(&#39;Press here&#39;),
);
}
}

I tried to insert:

  • regarding "ButtonA" the callBack function to onPressed and I declared the function before the override something like:
  final String TestoCheVorreiComparisse;
final Function callbackFunction;
const BottoneA({Key? key, required this.TestoCheVorreiComparisse, required this.callbackFunction}) : super(key: key);
  • as for "ColumnDX" before the override something like this:
String TestoCheVorreiComparisse=&quot;Vediamo se funziona&quot;;
callback(varTestoSostitutivo){
setState(() {
TestoCheVorreiComparisse=varTestoSostitutivo;
});
}

I am told, and I understand why, that there is no callback function in "buttonA"... How can I do this? Thank you!

答案1

得分: 0

你可以使用 Provider,它们的值是全局的,因此您可以在任何地方使用它们,并且可以在不使用 StatefulWidget 的情况下更新状态事件。
这是链接:Provider

英文:

You can use Provider and their values are global so you may use them anywhere where you want and can update state event without StatefulWidget.
here is the link:Provider

答案2

得分: 0

不使用第三方包,您可以将状态提升到它们的第一个共同父级,并将状态/修改函数传递给这两个元素。

英文:

Without using third party packages, you can lift your state to their first common parent and pass the state/modification functions down to both elements.

答案3

得分: 0

以下是翻译好的部分:

  • If you like to just get the tab event you can use VoidCallback, to pass data you need to use Function() callback.

    • 如果您只想获取选项卡事件,您可以使用 VoidCallback,如果需要传递数据,您需要使用 Function() 回调。
  • While the widget is nested, it you need to pass function on child.

    • 当小部件嵌套时,您需要在子级上传递函数。
  • Here is the demo using both approach, But for project level you may choose state management like riverpod/bloc.

    • 这是使用两种方法的演示,但对于项目级别,您可以选择状态管理,比如riverpod/bloc。
  • void main() 函数没有进行翻译。

  • class MyApp extends StatelessWidget 类没有进行翻译。

  • class HomePage extends StatefulWidget 类没有进行翻译。

  • class HomePageState extends State<HomePage> 类没有进行翻译。

  • String TestoADestra = 'TestoInizialeADestra'; 没有进行翻译。

  • class ColonnaDx extends StatefulWidget 类没有进行翻译。

  • class ColonnaDxState extends State<ColonnaDx> 类没有进行翻译。

  • class ColonnaSx extends StatelessWidget 类没有进行翻译。

  • class BottoneA extends StatelessWidget 类没有进行翻译。

  • class BottoneB extends StatelessWidget 类没有进行翻译。

英文:

If you like to just get the tab event you can use VoidCallback, to pass data you need to use Function() callback. While the widget is nested, it you need to pass function on child. Here is the demo using both approach, But for project level you may choose state management like riverpod/bloc

import &#39;package:flutter/cupertino.dart&#39;;
import &#39;package:flutter/material.dart&#39;;
import &#39;dart:math&#39; as math;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: &#39;Flutter layout demo&#39;,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  HomePageState createState() =&gt; HomePageState();
}

class HomePageState extends State&lt;HomePage&gt; {
  String TestoADestra = &#39;TestoInizialeADestra&#39;;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Row(
        children: [
          ColonnaSx(
            onButtonTapA: () {
              setState(() {
                TestoADestra = &quot;update value&quot;;
              });
            },
            onButtonTapB: (data) {
              setState(() {
                TestoADestra = &quot;update value ${data}&quot;;
              });
            },
          ),
          ColonnaDx(data: TestoADestra),
        ],
      ),
    );
  }
}

class ColonnaDx extends StatefulWidget {
  const ColonnaDx({super.key, required this.data});

  final String data;

  @override
  ColonnaDxState createState() =&gt; ColonnaDxState();
}

class ColonnaDxState extends State&lt;ColonnaDx&gt; {
  @override
  Widget build(BuildContext context) {
    return Expanded(
      flex: 4,
      child: Container(
        decoration: const BoxDecoration(
          color: Colors.blue,
        ),
        child: Column(
          children: [
            Expanded(
              child: Center(
                child: Text(widget.data),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class ColonnaSx extends StatelessWidget {
  final VoidCallback onButtonTapA;
  final Function(int data) onButtonTapB;

  const ColonnaSx({
    super.key,
    required this.onButtonTapA,
    required this.onButtonTapB,
  });
  @override
  Widget build(BuildContext context) {
    return Expanded(
      flex: 1,
      child: Container(
        decoration: BoxDecoration(
          color: Colors.red,
        ),
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            BottoneA(onButtonTap: onButtonTapA),
            BottoneB(onButtonTap: onButtonTapB),
          ],
        ),
      ),
    );
  }
}

class BottoneA extends StatelessWidget {
  final VoidCallback onButtonTap;

  const BottoneA({super.key, required this.onButtonTap});
  @override
  Widget build(BuildContext context) {
    return TextButton(
      style: ButtonStyle(
        foregroundColor:
            MaterialStateProperty.all&lt;Color&gt;(Color.fromARGB(255, 72, 3, 201)),
      ),
      onPressed: onButtonTap,
      child: Text(&#39;Press here&#39;),
    );
  }
}

class BottoneB extends StatelessWidget {
  final Function(int data) onButtonTap;

  const BottoneB({super.key, required this.onButtonTap});
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () {
        onButtonTap(math.Random().nextInt(55555));
      },
      child: Text(&#39;Press to pass int&#39;),
    );
  }
}

huangapple
  • 本文由 发表于 2023年3月7日 02:38:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75654617.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定