Home > database >  Error in Flutter: A non-null value must be returned since the return type 'Widget' doesn&#
Error in Flutter: A non-null value must be returned since the return type 'Widget' doesn&#

Time:03-06

This class in main.dart won't work.

import 'package:flutter/material.dart';

void main() {
  runApp(new MyFlutterApp()

  );
}

class MyFlutterApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    MaterialApp(
        title: "My Flutter Application",
        home: Scaffold(
          appBar: AppBar(title: Text("hello"),),
          body: Material(
              color: Colors.lightBlueAccent,
              child:  Center(
                  child: Text(
                    "Hello Flutter",
                    textDirection: TextDirection.ltr,
                    style: TextStyle(color: Colors.white, fontSize: 40.0,),
                  )
              )
          ) ,
        )
    );

  }

}

That's it. The entire main.dart. The class won't work. It shows:

Error: A non-null value must be returned since the return type 'Widget' doesn't allow null.
 - 'Widget' is from 'package:flutter/src/widgets/framework.dart' ('../../flutter_projects/flutter/packages/flutter/lib/src/widgets/framework.dart').
  Widget build(BuildContext context) {

CodePudding user response:

build method has to return a widget. Try

class MyFlutterApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: "My Flutter Application",
        home: Scaffold(
          appBar: AppBar(title: Text("hello"),),
          body: Material(
              color: Colors.lightBlueAccent,
              child:  Center(
                  child: Text(
                    "Hello Flutter",
                    textDirection: TextDirection.ltr,
                    style: TextStyle(color: Colors.white, fontSize: 40.0,),
                  )
              )
          ) ,
        )
    );

  }

}

CodePudding user response:

The issue is in the lines:

@override
  Widget build(BuildContext context) {
    MaterialApp(
        title: "My Flutter Application",

The problem is that the line

Widget build(BuildContext context) {}

is a function and as pretty much in any language function signature the return type of function is the very first part which here is Widget.

As dart is a statically typed language and if some method/function has a return type you need to return is else it throws compile time error.

Whereas in you function you do not return anything you are just declaring the MaterialApp instance. What exactly should have be done was either to user return before MaterialApp which should look like:

@override
Widget build(BuildContext context){
  return MaterialApp();//please not these semicolons are must if using return keyboard
}

or

The second work around is to use fat arrow operator => for inline returns. Which looks like:

@override
Widget build(BuildContext context) => MaterialApp()
  • Related