Home > Blockchain >  Error "The body might complete normally, causing 'null' to be returned, but the retur
Error "The body might complete normally, causing 'null' to be returned, but the retur

Time:08-06

There are red dots under the _paMachine. How do I fix this error so the paMachine prints a new string every time I press the floating action button?

class _MyHomePageState extends State<MyHomePage> {
  String *_paMachine()* {
    setState(() {
      var bar = Random().nextInt(26)   97;
      var nar = Random().nextInt(26)   97;
      String foo =
          '${String.fromCharCode(nar)}om ${String.fromCharCode(bar)}ey';
      print(foo);
    });
  }

CodePudding user response:

Just add a return to your function

    class _MyHomePageState extends State<MyHomePage> {
          String *_paMachine()* {

  var bar = Random().nextInt(26)   97;
              var nar = Random().nextInt(26)   97;
              String foo =
                  '${String.fromCharCode(nar)}om ${String.fromCharCode(bar)}ey';
              print(foo);
            setState(() {
            
            });
          return foo;
          }

CodePudding user response:

By adding a prefix String you are mentioning the engine that the method will return a value of type String. So the method will expect you to return a string.. If you don't wish to return anything from the method you can remove the String and write it like

paMachine() {
    setState(() {
      var bar = Random().nextInt(26)   97;
      var nar = Random().nextInt(26)   97;
      String foo =
          '${String.fromCharCode(nar)}om ${String.fromCharCode(bar)}ey';
      print(foo);
    });
}

If you wish to return a value from the method add a return at the end of the method like

String paMachine() {
    String foo = "";
    setState(() {
      var bar = Random().nextInt(26)   97;
      var nar = Random().nextInt(26)   97;
     foo =
          '${String.fromCharCode(nar)}om ${String.fromCharCode(bar)}ey';
      print(foo);
    });
  return foo;
}
  • Related