【问题标题】:How to change value of variable in statefull widget from another widget如何从另一个小部件更改有状态小部件中变量的值
【发布时间】:2021-12-26 00:05:05
【问题描述】:

我在一个有状态的小部件中有一个变量,它包含一个字符串值。我从另一个飞镖文件中调用了一个小部件。我需要从此小部件更改有状态小部件中变量的值。我尝试过 valuelistanablebuilder 但它只在该 dart 文件中调用函数时才听值。请告诉我如何做的方法和示例代码。

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
          ],
        ),
      ),
    );
  }
}

在这个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', () {}),
      ],
    ),
  );
}

当调用这些按钮时,我需要从那个有状态的小部件中更改变量 currentPage 的值。

【问题讨论】:

  • 您是否考虑过将值作为构造函数参数传入?通常,通过在构造函数中指定参数来配置小部件。请在问题中发布您要执行的操作的代码。
  • 我已经编辑了这个问题。请看。
  • question 的答案应该会有所帮助。您基本上想将回调函数传递给调用父小部件的setState 的子小部件。
  • 你要回调吗,看这个问题,找ValueSeter。 stackoverflow.com/questions/54493002/…

标签: flutter dart


【解决方案1】:

首先,将您的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')),
        ],
      ),
    );
  }
}

然后在你的_HomeMobileState 类中,使用这个:

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

【讨论】:

  • 有人将小部件名称更改为ExtendedAppBar,我更正了最后一部分以反映新名称。
【解决方案2】:

您最好使用状态管理来获得更好的解决方案。检查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);
  }
}

【讨论】:

    猜你喜欢
    • 2021-12-26
    • 2021-07-20
    • 2020-07-31
    • 2019-12-17
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2019-10-06
    • 1970-01-01
    相关资源
    最近更新 更多