Home > Net >  Error :The body might complete normally, causing 'null' to be returned, but the return typ
Error :The body might complete normally, causing 'null' to be returned, but the return typ

Time:10-21

I'm using the new dart version <2.18.1> with null safety enabled.

this is my code

           import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:untitled3/product.dart';
import 'package:untitled3/product_db_helper.dart';

class ProductScreen extends StatefulWidget {
  const ProductScreen({Key? key}) : super(key: key);

  @override
  State<ProductScreen> createState() => _ProductScreenState();
}

class _ProductScreenState extends State<ProductScreen> {
  TextEditingController _idController = TextEditingController();
  TextEditingController _nameController = TextEditingController();
  TextEditingController _priceController = TextEditingController();
  TextEditingController _quantityController = TextEditingController();

  List<Product> productsList = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Product Screen'),
      ),
        body: Center(
          child: Column(
            children: [
              Expanded(child: ListView.builder(
                  itemCount: productsList.length,
                  itemBuilder: (BuildContext context , index){
                    if(productsList.isNotEmpty)
                    {
                      return GestureDetector(
                        child: Container(
                          decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(10)
                          ),
                        ),
                      );
                    }
                  }
                  ))
            ],
          ),
        ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          showProductDialogBox(context);
        },
        child: Icon(Icons.add),
        backgroundColor: Colors.blue,
      ),
    );
  }
//////////////////Show product dialog box ................ Name , Price , Quantity ............
  showProductDialogBox(BuildContext context)
  {
    Widget saveButton = TextButton(onPressed: (){
      if( _idController.text.isNotEmpty &&_nameController.text.isNotEmpty && _priceController.text.isNotEmpty
          && _quantityController.text.isNotEmpty)
        {
          Product product = Product(id: int.parse(_idController.text), name: _nameController.text, price: _priceController.text, quantity: int.parse(_quantityController.text));
          /*product.id =int.parse(_idController.text);
          product.name = _nameController.text;
          product.price = _priceController.text;
          product.quantity =int.parse(_quantityController.text);*/

          ProductDBHelper.instance.insertProduct(product).then((value){

            ProductDBHelper.instance.getProductList().then((value){

              setState(() {
                productsList = value;
              });
            });

            Navigator.pop(context);
          });
        }

    }, child: Text('Save'));

    Widget cancelButton = TextButton(onPressed: (){
      Navigator.of(context).pop();
    }, child: Text('Cancel'));

    AlertDialog productDetailsBox = AlertDialog(
      title: Text('Add new product'),
      content: Container(
        child: Wrap(
          children: [
            Container(
              child: TextFormField(
                controller: _nameController,
                decoration: InputDecoration(
                  labelText: 'Product Name'
                ),
              ),
            ),
            Container(
              child: TextFormField(
                controller: _priceController,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                    labelText: 'Product Price'
                ),
              ),
            ),
            Container(
              child: TextFormField(
                controller: _quantityController,
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                    labelText: 'Product Quantity'
                ),
              ),
            )
          ],
        ),
      ),
      actions: [
        saveButton ,
        cancelButton
      ],
    );
    
    showDialog(context: context, builder: (BuildContext context){
      return productDetailsBox;
    });
  }
}

I'm getting this error:

error: The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.

and this error in the Run log:

Launching lib\main.dart on Android SDK built for x86 in debug mode... Running Gradle task 'assembleDebug'... lib/product_screen.dart:32:32: 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' ('../../Documents/flutter/Flutter/flutter_windows_3.3.2-stable/flutter/packages/flutter/lib/src/widgets/framework.dart'). itemBuilder: (BuildContext context , index){ ^

FAILURE: Build failed with an exception.

  • Where: Script 'C:\Users\induw\Documents\flutter\Flutter\flutter_windows_3.3.2-stable\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1159

  • What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command 'C:\Users\induw\Documents\flutter\Flutter\flutter_windows_3.3.2-stable\flutter\bin\flutter.bat'' finished with non-zero exit value 1

  • Try:

Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

BUILD FAILED in 2m 59s Exception: Gradle task assembleDebug failed with exit code

Expanded(child: ListView.builder(
              itemCount: productsList.length,
              itemBuilder: (BuildContext context , index)...{...
                if(productsList.isNotEmpty)
                {
                  return GestureDetector(
                    child: Container(
                      decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(10)
                      ),
                    ),
                  );
                }
              }
              ))

This is where the error is. I put .... where the red underline is. please help me I'm a beginner.

CodePudding user response:

You need to return a widget from itemBuilder, current snippet return only when if (productsList.isNotEmpty) { is satisfied. you can return a default widget on else state.

itemCount: productsList.length,
itemBuilder: (BuildContext context, index) {
  if (productsList.isNotEmpty) {
    return GestureDetector(
      child: Container(
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10)),
      ),
    );
  }
  return Text("It is empty");
})
  • Related