如何在子窗口小部件上编辑值 [英] how to edit value at the child widget

查看:66
本文介绍了如何在子窗口小部件上编辑值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试编辑子窗口小部件的值,我可以使用StatefulWidget父级来完成此操作,但是我想使用StatelessWidget父级来执行此操作,而无需使用全局值

i try to edit the value of the child widget, i can do it with StatefulWidget parent but i want to do it with StatelessWidget parent and without using global value

    class Homepage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          FlatButton(child: Text('addFile'), onPressed: () {}),
          FlatButton(child: Text('deleteFile'), onPressed: () {})
        ],
      ),
      body: Child(),
    );
  }
}

class Child extends StatefulWidget {
  @override
  _ChildState createState() => _ChildState();
}

class _ChildState extends State<Child> {
  var hasFile = true;
  @override
  Widget build(BuildContext context) {
    return hasFile ? Text('has a file') : Text("no File");
  }
}

推荐答案

您在想错误的方式.子aka Text()应该从由应用程序管理或至少由上面的小部件管理的模型中获取其值.我将使用提供程序包 https://pub.dev/packages/provider 并执行以下操作:

You are thinking the wrong way. Child aka Text() should get its value from a model which is managed by the application or at least managed by the widget above. I would go with the provider package https://pub.dev/packages/provider and do this:

import 'package:provider/provider.dart';
import 'package:flutter/material.dart';


class MyState with ChangeNotifier {
  String _myText;

  MyState(this._myText);

  getMyText() => _myText;

  void changeText(String newText) {
    _myText = newText;
    notifyListeners();
  }
}

class Homepage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          ChangeNotifierProvider(builder: (_) => MyState("initial Text")),
        ],
        child: Scaffold(
          appBar: AppBar(
            actions: <Widget>[
              FlatButton(
                  child: Text('addFile'),
                  onPressed: () {
                    Provider.of<MyState>(context).changeText("addFile");
                  }),
              FlatButton(
                  child: Text('deleteFile'),
                  onPressed: () {
                    Provider.of<MyState>(context).changeText("deleteFile");
                  })
            ],
          ),
          body: Child(),
        ));
  }
}

class Child extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    MyState myState = Provider.of<MyState>(context);
    return Text(myState.getMyText());
  }
}

此代码在没有IDE支持的情况下甚至无法编译运行.但这应该可以指引您正确的方向.

This is coded without IDE support or even compiling and running. But it should get you to the right direction.

这篇关于如何在子窗口小部件上编辑值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆