从Stateless Widget更新Stateful Widget - Flutter

时间:2018-03-23 10:06:59

标签: android widget dart flutter

目前我正在尝试在Flutter中构建一个简单的计算器应用程序。 我遇到了一个问题,我试图在包含它的无状态扩展中更新状态窗口小部件的内容。 我使用了我的状态窗口小部件的实例。但是,它没有按预期更新。

import 'package:calculator/calcLogic.dart';
import 'package:flutter/material.dart';

class CalcHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text('Calculator'),
        ),
        body: new CalcLayout());
  }
}

class CalcLayout extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Column(children: getColumns());
  }

  List<Widget> getColumns() {
    var labels = [
      "1", "2", "3", "+",
      "4", "5", "6", "-",
      "7", "8", "9", "*",
      "C", "0", "=", "/",
      ""];

    List<Widget> list = new List<Widget>();

    list.add(new ResultString());
    for (int i = 0; i < 4; i++) {
      list.add(new Expanded(
          child: new Row(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: new List<Widget>.generate(4, (ind) {
                var row = labels.sublist(i * 4, i * 4 + 4);
                var text = row[ind];
                return new Expanded(
                    child: new RaisedButton(
                        onPressed: () => _state.doUpdate(text),
                        child: new Text('$text')));
              }))));
    }

    return list;
  }
}

class ResultString extends StatefulWidget {
  @override
  createState() => new ResultState();
}

class ResultState extends State<ResultString> {
  var _text = CalcLogic.getResult();

  @override
  Widget build(BuildContext context) {
    return new Center(
      child: new Text(
        "$_text",
        style: new TextStyle(fontSize: 40.0),
      ),
      heightFactor: 2.0,
    );
  }

  void doUpdate(String text) {
    setState(() {
      CalcLogic.doButton(text);
      _text = CalcLogic.getResult();
    });
  }
}

ResultState _state = new ResultState();

有没有人知道如何解决这个问题,最好不要将整个布局转换为有状态布局?

1 个答案:

答案 0 :(得分:0)

#ifndef GLOBAL_h
#define GLOBAL_h

#include<QQueue>
#include<QMutex>
#include <QtGlobal>  // you must have to include.
#include <QWaitCondition> 


static QQueue <QString> The_Queue;
static QMutex m_mutex;
static QWaitCondition m_QueueEmpty;

#endif // GLOBAL_h

现在你的国家小屋创造你的功能

#include <QCoreApplication>
#include "popmsg.h"
#include "pushmsg.h"
#include "global.h"   


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    popmsg m_pop;  //Thread 1
    pushmsg m_push;//Thread 2
    m_push.start();
    m_pop.start();
    m_push.wait();
    m_pop.wait();

    return a.exec();
}