简体   繁体   English

如何从另一个小部件更改有状态小部件中变量的值

[英]How to change value of variable in statefull widget from another widget

I have a variable inside a statefull widget which contains a string value.我在包含字符串值的 statefull 小部件中有一个变量。 I called a widget from another dart file.我从另一个 dart 文件调用了一个小部件。 I need to change the value of the variable in statefull widget from this widget.我需要从此小部件更改 statefull 小部件中变量的值。 I have tries valuelistanablebuilder but it is only listen to value when function called inside that dart file.我尝试过valuelistanablebuilder但它只在该 dart 文件中调用函数时监听值。 Please tell me a way and example code on how to do it.请告诉我如何做到这一点的方法和示例代码。

import 'package:flutter/material.dart';
import 'package:messaging_service/components/app_bar.dart';
import 'package:messaging_service/components/home_pages/all_messages.dart';
import 'package:messaging_service/components/home_pages/stories.dart';
import 'package:messaging_service/components/search_bar.dart';
import 'package:messaging_service/components/strings.dart';
import 'package:messaging_service/components/style.dart';

class HomeMobile extends StatefulWidget {
  const HomeMobile({Key? key}) : super(key: key);

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

class _HomeMobileState extends State<HomeMobile> {
  var currentPage = 'all';
  TextEditingController searchChatController = TextEditingController();
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: lightColor,
      appBar: AppBarHomeMobile(context),
      body: SingleChildScrollView(
        child: Column(
          children: [
            AppBarHomeExtend(),
            const SizedBox(
              height: 10,
            ),
            //To Call a Widget
          ],
        ),
      ),
    );
  }
}

In this AppBarHomeExtend() has some buttons..在这个AppBarHomeExtend() 中有一些按钮..

Widget AppBarHomeExtend() {
  return Container(
    height: 80,
    decoration: BoxDecoration(
        color: lightColor,
        boxShadow: [
          BoxShadow(color: darkColor, blurRadius: 5),
        ],
        borderRadius: const BorderRadius.only(
            bottomLeft: Radius.circular(35), bottomRight: Radius.circular(35))),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        HRButtons('All Messages', () {}),
        HRButtons('Groups', () {  }),
        HRButtons('Stories', () {}),
        HRButtons('Calls', () {}),
      ],
    ),
  );
}

When called these buttons I need to change the value of variable currentPage from that statefull widget.当调用这些按钮时,我需要从该 statefull 小部件更改变量 currentPage 的值。

First, turn your AppBarHomeExtend into a proper widget which takes a callback function as argument:首先,将你的AppBarHomeExtend变成一个合适的小部件,它接受一个回调函数作为参数:

import 'package:flutter/material.dart';

class ExtendedAppBar extends StatelessWidget {
  final void Function(String) setPage;

  const ExtendedAppBar({Key? key, required this.setPage}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 80,
      decoration: BoxDecoration(
          color: Colors.blue.shade50,
          boxShadow: [
            BoxShadow(color: Colors.blue.shade900, blurRadius: 5),
          ],
          borderRadius: const BorderRadius.only(bottomLeft: Radius.circular(35), bottomRight: Radius.circular(35))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          HRButtons('All Messages', () => setPage('All Messages')),
          HRButtons('Groups', () => setPage('Groups')),
          HRButtons('Stories', () => setPage('Stories')),
          HRButtons('Calls', () => setPage('Calls')),
        ],
      ),
    );
  }
}

Then in your _HomeMobileState class, use this:然后在你的_HomeMobileState类中,使用这个:

ExtendedAppBar(
  setPage: (String value) {
    setState(() {
      currentPage = value;
    });
  },
),

you better need to use a state management to get a better solution .您最好需要使用状态管理来获得更好的解决方案。 check this package检查这个包

 floatingActionButton: FloatingActionButton(
    key: const Key('increment_floatingActionButton'),

    /// Calls `context.read` instead of `context.watch` so that it does not rebuild
    /// when [Counter] changes.
    onPressed: () => context.read<Counter>().increment(),
    tooltip: 'Increment',
    child: const Icon(Icons.add),
  ),

  class Count extends StatelessWidget {
  const Count({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
     return Text(

    /// Calls `context.watch` to make [Count] rebuild when [Counter]      changes.
       '${context.watch<Counter>().count}',
        key: const Key('counterState'),
        style: Theme.of(context).textTheme.headline4);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter:: 更改未来列表中有状态小部件的初始状态值 - Flutter :: change value in initialstate in statefull widget from future list 如何从同一屏幕上的另一个有状态小部件接收数据? - How to receive data from another statefull widget on the same screen? 从有状态的父级修改有状态的子小部件中的值 - Modify value in statefull child widget from its statefull parent 将变量从有状态小部件传递到 state - pass a variable from a statefull widget to state 如何从另一个小部件更改有状态小部件的变量? - How to change variable of a stateful widget from another widget? 如何在 flutter 中将 id 从有状态小部件获取到无状态小部件? - how to get the id from statefull widget to stateless widget in flutter? 为什么当我在其小部件中调用 Flutter 有状态小部件时,它没有更改另一个有状态小部件的 state - Why Flutter statefull widget didn't change the state of another statefull widget when I call it inside its widget 如何在一个小部件和另一个小部件中设置变量值? - How to set a variable value in a widget and in another widget? 从无状态小部件调用有状态小部件的 setState - Call a setState of a statefull widget from the stateless widget Flutter 将数据从一个 class 传递到另一个(有状态小部件) - Flutter pass data from one class to another(statefull widget)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM