setState () не может ссылаться на флаттер - PullRequest
1 голос
/ 29 апреля 2020

Я кодирую это приложение на VScode. Когда я пытаюсь использовать setState () внутри функции createButton () (расположенной в конце кода между прочим), она показывает голубую волнистую линию под надписью «На объявление« setState »нет ссылки». Как использовать setState (), чтобы он ссылался на кнопку, созданную функцией createButton (). Спасибо за помощь :)

import 'package:flutter/material.dart';

void main() => runApp(MainScreen());

class MainScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SafeArea(
        child: Scaffold(
          body: Column(
            // crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[

/* -------------------------------------------------------------------------- */
/*                               Display section                              */
/* -------------------------------------------------------------------------- */

              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: <Widget>[
                  Text('Hello World', style: TextStyle(fontSize: 50)),
                  SizedBox(height: 20),
                  Text('I\'m small', style: TextStyle(fontSize: 20)),
                  Container(width: double.infinity, height: 200),               
                 ],
              ),

/* -------------------------------------------------------------------------- */
/*                               Button section                               */
/* -------------------------------------------------------------------------- */

              Expanded(
                  child: Row(
                  children: <Widget>[

/* -------------------------------- Column 1 -------------------------------- */

                    createButtonColumn(buttonAmount: 4, buttonContents: [
                        Text('+', style: TextStyle(fontSize: 25, color: Colors.black54)), 
                        Text('8', style: TextStyle(fontSize: 25, color: Colors.white54)),
                        Text('4', style: TextStyle(fontSize: 25, color: Colors.white54)),
                        Text('0', style: TextStyle(fontSize: 25, color: Colors.white54))
                      ],
                      buttonColors: [Colors.redAccent, Colors.black, Colors.black, Colors.black],

                    ),

/* -------------------------------- Column 2 -------------------------------- */

                    createButtonColumn(buttonAmount: 4, buttonContents: [
                        Text('-', style: TextStyle(fontSize: 35, color: Colors.black54)), 
                        Text('9', style: TextStyle(fontSize: 25, color: Colors.white54)), 
                        Text('5', style: TextStyle(fontSize: 25, color: Colors.white54)),
                        Text('1', style: TextStyle(fontSize: 25, color: Colors.white54))
                      ],
                      buttonColors: [Colors.redAccent, Colors.black, Colors.black, Colors.black],
                    ),

/* -------------------------------- Column 3 -------------------------------- */

                    createButtonColumn(buttonAmount: 4, buttonContents: [
                        Text('*', style: TextStyle(fontSize: 25, color: Colors.black54)), 
                        Text('<--', style: TextStyle(fontSize: 25, color: Colors.white54)),
                        Text('6', style: TextStyle(fontSize: 25, color: Colors.white54)),
                        Text('2', style: TextStyle(fontSize: 25, color: Colors.white54))
                      ],
                      buttonColors: [Colors.redAccent, Colors.black, Colors.black, Colors.black],
                    ),

/* -------------------------------- Column 4 -------------------------------- */

                    createButtonColumn(buttonAmount: 4, buttonContents: [
                        Text('/', style: TextStyle(fontSize: 25, color: Colors.black54)), 
                        Text('AC', style: TextStyle(fontSize: 25, color: Colors.white54)),
                        Text('7', style: TextStyle(fontSize: 25, color: Colors.white54)),
                        Text('3', style: TextStyle(fontSize: 25, color: Colors.white54))
                      ],
                      buttonColors: [Colors.redAccent, Colors.black, Colors.black, Colors.black],
                    ),

/* -------------------------------- Column 5 -------------------------------- */

                    createButtonColumn(buttonAmount: 4, buttonContents: [
                        Text('=', style: TextStyle(fontSize: 25, color: Colors.black54)), 
                        Text('(', style: TextStyle(fontSize: 25, color: Colors.black54)),
                        Text(')', style: TextStyle(fontSize: 25, color: Colors.black54)),
                        Text('.', style: TextStyle(fontSize: 35, color: Colors.black54))
                      ],
                      buttonColors: [Colors.yellow[300], Colors.redAccent, Colors.redAccent, Colors.redAccent],
                    )
                  ],
                ),
              )
            ],
          )
        )
      )
    );
  }
}


/* -------------------------------------------------------------------------- */
/*                              Custom functions                              */
/* -------------------------------------------------------------------------- */

createButtonColumn({ int buttonAmount, List<Widget> buttonContents, bool buttonContentsAreSame = false, List<Color> buttonColors, bool buttonColorsAreSame = false, List<String> actionList }) {
  List<Widget> buttonList = [];

  if (!buttonContentsAreSame || !buttonColorsAreSame) {
    for (int i = 0; i < buttonContents.length; i++) {
      buttonList.add(createButton(content: buttonContents[i], color: buttonColors[i], action: actionList[i]));
    }
  } else {
      for (int x = 1; x <= buttonAmount; x++) {
        buttonList.add(createButton(content: buttonContents[0]));
      }      
  }

  return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: buttonList
      ),
  );
}

createButton({ int flex = 1, Widget content, Color color, String action }) {
  return Expanded(
    child: RaisedButton(
      onPressed: () {
        setState() {

        }    
      },
      child: content,
      color: color
    ),
    flex: flex,
  );
}```

Ответы [ 2 ]

0 голосов
/ 29 апреля 2020

Проблема в том, что вы используете класс без сохранения состояния. Измените его на Stateful, и он примет setstate ().

import 'package:flutter/material.dart';

void main() => runApp(MainScreen());

class MainScreen extends StatefulWidget {
  @override
  _MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: SafeArea(
        child: Scaffold(
          body: Column(
            // crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
/* -------------------------------------------------------------------------- */
/*                               Display section                              */
/* -------------------------------------------------------------------------- */

              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: <Widget>[
                  Text('Hello World', style: TextStyle(fontSize: 50)),
                  SizedBox(height: 20),
                  Text('I\'m small', style: TextStyle(fontSize: 20)),
                  Container(width: double.infinity, height: 200),
                ],
              ),

/* -------------------------------------------------------------------------- */
/*                               Button section                               */
/* -------------------------------------------------------------------------- */

              Expanded(
                child: Row(
                  children: <Widget>[
/* -------------------------------- Column 1 -------------------------------- */

                    createButtonColumn(
                      buttonAmount: 4,
                      buttonContents: [
                        Text('+',
                            style:
                                TextStyle(fontSize: 25, color: Colors.black54)),
                        Text('8',
                            style:
                                TextStyle(fontSize: 25, color: Colors.white54)),
                        Text('4',
                            style:
                                TextStyle(fontSize: 25, color: Colors.white54)),
                        Text('0',
                            style:
                                TextStyle(fontSize: 25, color: Colors.white54))
                      ],
                      buttonColors: [
                        Colors.redAccent,
                        Colors.black,
                        Colors.black,
                        Colors.black
                      ],
                    ),

/* -------------------------------- Column 2 -------------------------------- */

                    createButtonColumn(
                      buttonAmount: 4,
                      buttonContents: [
                        Text('-',
                            style:
                                TextStyle(fontSize: 35, color: Colors.black54)),
                        Text('9',
                            style:
                                TextStyle(fontSize: 25, color: Colors.white54)),
                        Text('5',
                            style:
                                TextStyle(fontSize: 25, color: Colors.white54)),
                        Text('1',
                            style:
                                TextStyle(fontSize: 25, color: Colors.white54))
                      ],
                      buttonColors: [
                        Colors.redAccent,
                        Colors.black,
                        Colors.black,
                        Colors.black
                      ],
                    ),

/* -------------------------------- Column 3 -------------------------------- */

                    createButtonColumn(
                      buttonAmount: 4,
                      buttonContents: [
                        Text('*',
                            style:
                                TextStyle(fontSize: 25, color: Colors.black54)),
                        Text('<--',
                            style:
                                TextStyle(fontSize: 25, color: Colors.white54)),
                        Text('6',
                            style:
                                TextStyle(fontSize: 25, color: Colors.white54)),
                        Text('2',
                            style:
                                TextStyle(fontSize: 25, color: Colors.white54))
                      ],
                      buttonColors: [
                        Colors.redAccent,
                        Colors.black,
                        Colors.black,
                        Colors.black
                      ],
                    ),

/* -------------------------------- Column 4 -------------------------------- */

                    createButtonColumn(
                      buttonAmount: 4,
                      buttonContents: [
                        Text('/',
                            style:
                                TextStyle(fontSize: 25, color: Colors.black54)),
                        Text('AC',
                            style:
                                TextStyle(fontSize: 25, color: Colors.white54)),
                        Text('7',
                            style:
                                TextStyle(fontSize: 25, color: Colors.white54)),
                        Text('3',
                            style:
                                TextStyle(fontSize: 25, color: Colors.white54))
                      ],
                      buttonColors: [
                        Colors.redAccent,
                        Colors.black,
                        Colors.black,
                        Colors.black
                      ],
                    ),

/* -------------------------------- Column 5 -------------------------------- */

                    createButtonColumn(
                      buttonAmount: 4,
                      buttonContents: [
                        Text('=',
                            style:
                                TextStyle(fontSize: 25, color: Colors.black54)),
                        Text('(',
                            style:
                                TextStyle(fontSize: 25, color: Colors.black54)),
                        Text(')',
                            style:
                                TextStyle(fontSize: 25, color: Colors.black54)),
                        Text('.',
                            style:
                                TextStyle(fontSize: 35, color: Colors.black54))
                      ],
                      buttonColors: [
                        Colors.yellow[300],
                        Colors.redAccent,
                        Colors.redAccent,
                        Colors.redAccent
                      ],
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
  /* -------------------------------------------------------------------------- */
/*                              Custom functions                              */
/* -------------------------------------------------------------------------- */

  createButtonColumn(
      {int buttonAmount,
      List<Widget> buttonContents,
      bool buttonContentsAreSame = false,
      List<Color> buttonColors,
      bool buttonColorsAreSame = false,
      List<String> actionList}) {
    List<Widget> buttonList = [];

    if (!buttonContentsAreSame || !buttonColorsAreSame) {
      for (int i = 0; i < buttonContents.length; i++) {
        buttonList.add(createButton(
            content: buttonContents[i],
            color: buttonColors[i],
            action: actionList[i]));
      }
    } else {
      for (int x = 1; x <= buttonAmount; x++) {
        buttonList.add(createButton(content: buttonContents[0]));
      }
    }

    return Expanded(
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch, children: buttonList),
    );
  }

  createButton({int flex = 1, Widget content, Color color, String action}) {
    return Expanded(
      child: RaisedButton(
          onPressed: () {
            setState(() {
              debugPrint('Hello');
            });
          },
          child: content,
          color: color),
      flex: flex,
    );
  }
}
0 голосов
/ 29 апреля 2020

только виджет Statefull может обрабатывать setState()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...