4

hey guys i m new in dart and flutter when i run the project i face an error that enter image description heresays unexpected null value i couldn't find where is the mistake, i think the problem is in Null Safety. I have three classes two of them are for screen and one is a modle,

    import 'package:enpc_site/screens/body_page.dart';
import 'package:enpc_site/screens/navigate_bar.dart';
import 'package:enpc_site/screens/our_services.dart';
import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(150),
        child: AppBar(
          backgroundColor: Colors.black,
          flexibleSpace: NavigateBar(),
        ),
      ),
      body: Container(
        decoration: BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
              Color.fromARGB(255, 0, 0, 0),
              Color.fromARGB(255, 49, 8, 8)
            ])),
        height: double.infinity,
        child: Padding(
            padding: EdgeInsets.symmetric(vertical: 20, horizontal: 100),
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Padding(
                    padding: const EdgeInsets.only(top: 200),
                    child: WhoWe(),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 200),
                    child: OurServices(), // here i'm calling my second screen class
                  )
                ],
              ),
            )),
      ),
    );
  }
}

the second class

import 'package:enpc_site/models/products.dart';
import 'package:flutter/material.dart';
class OurServices extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraint) {
        return BodyPage();
      },
    );
  }
}

class BodyPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
     Products? product;
     String image = product!.products[0].image;
     String name = product.products[0].name;
     String desc = product.products[0].discription;
    return Container(
      width: double.infinity,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            "SERVICES",
            style: TextStyle(fontSize: 25, color: Colors.white),
          ),
          SizedBox(
            height: 20,
          ),
          Text(
            "CE QUE NOUS PRODUISON",
            style: TextStyle(
                fontSize: 40, fontWeight: FontWeight.bold, color: Colors.white),
          ),
          SizedBox(
            height: 40,
          ),
          SingleChildScrollView(
            scrollDirection: Axis.horizontal,
              child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  height: 500,
                  width: 500,
                  decoration: BoxDecoration(
                    color: Color.fromARGB(100, 240, 240, 240),
                    borderRadius: BorderRadius.circular(10)
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(40),
                    
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Image.asset('$image' , width: 400, height: 300,),
                        Text(
                          '$name',
                          style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
                        ),
                        RichText(
                            text: TextSpan(text: '$desc',
                            style: TextStyle(color: Colors.white, fontSize: 15), ),
                            
                          ),
                      ],
                    ),
                  ),
                ),
                SizedBox(
                  width: 20,
                ),
                Container(
                  height: 500,
                  width: 500,
                  decoration: BoxDecoration(
                    color: Color.fromARGB(100, 240, 240, 240),
                    borderRadius: BorderRadius.circular(10)
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(40),
                    
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Image.asset('assets/images/port.png', width: 400, height: 300,),
                        Text(
                          'Gaine Plastic',
                          style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
                        ),
                        RichText(
                            text: TextSpan(text: 'Les gaines ou fourreaux de protection utilisables dans l\'habitat dépendent de la norme NF C 15-100 relative aux installations électriques à basse tension',
                            style: TextStyle(color: Colors.white, fontSize: 15), ),
                            
                          ),
                      ],
                    ),
                  ),
                ),
                SizedBox(
                  width: 20,
                ),
                Container(
                  height: 500,
                  width: 500,
                  decoration: BoxDecoration(
                    color: Color.fromARGB(100, 240, 240, 240),
                    borderRadius: BorderRadius.circular(10)
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(40),
                    
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Image.asset('assets/images/Sheet.png', width: 400, height: 300,),
                        Text(
                          'Gaine Plastic',
                          style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
                        ),
                        RichText(
                            text: TextSpan(text: 'Les gaines ou fourreaux de protection utilisables dans l\'habitat dépendent de la norme NF C 15-100 relative aux installations électriques à basse tension',
                            style: TextStyle(color: Colors.white, fontSize: 15), ),
                            
                          ),
                      ],
                    ),
                  ),
                ),
                SizedBox(width: 20,),
                Container(
                  height: 500,
                  width: 500,
                  decoration: BoxDecoration(
                    color: Color.fromARGB(100, 240, 240, 240),
                    borderRadius: BorderRadius.circular(10)
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(40),
                    
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Image.asset('assets/images/gainePlastic.png', width: 400, height: 300,),
                        Text(
                          'Gaine Plastic',
                          style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold),
                        ),
                        RichText(
                            text: TextSpan(text: 'Les gaines ou fourreaux de protection utilisables dans l\'habitat dépendent de la norme NF C 15-100 relative aux installations électriques à basse tension',
                            style: TextStyle(color: Colors.white, fontSize: 15), ),
                            
                          ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}

and this is the model class Product

    class Products {
    final String name, discription;
    final String image;
  


  Products(
      { required this.name, required this.discription, required this.image});
List<Products> products = [
    Products(
        name: 'Gaine Plastic',
        discription:
            'Les gaines ou fourreaux de protection utilisables dans l\'habitat dépendent de la norme NF C 15-100 relative aux installations électriques à basse tension ',
        image: 'assets/images/gainePlastic.png'),
    Products(
        name: 'Gaine Plastic',
        discription:
            'Les gaines ou fourreaux de protection utilisables dans l\'habitat dépendent de la norme NF C 15-100 relative aux installations électriques à basse tension ',
        image: 'assets/images/port.png'),
    Products(
        name: 'Gaine Plastic',
        discription:
            'Les gaines ou fourreaux de protection utilisables dans l\'habitat dépendent de la norme NF C 15-100 relative aux installations électriques à basse tension ',
        image: 'assets/images/Sheet.png'),
    Products(
        name: 'Gaine Plastic',
        discription:
            'Les gaines ou fourreaux de protection utilisables dans l\'habitat dépendent de la norme NF C 15-100 relative aux installations électriques à basse tension ',
        image: 'assets/images/gainePlastic.png'),
    Products(
        name: 'Gaine Plastic',
        discription:
            'Les gaines ou fourreaux de protection utilisables dans l\'habitat dépendent de la norme NF C 15-100 relative aux installations électriques à basse tension ',
        image: 'assets/images/gainePlastic.png'),
  ];
  
}
Boukhames Karim
  • 53
  • 1
  • 1
  • 3

2 Answers2

0

You are not initialising your second class, you are not initialising your 'product' variable to access the list in your model class. It is indeed set to null. To fix this, first create an instance of the model class 'Products' and then using that instance variable, access the list in the class. Assign that list to a variable and use that in your UI. Also, it is recommended that you declare your variables outside the 'build' method because the build methods runs every time the UI needs to be refreshed, which could potentially reset your values. This may not be the desired behaviour, but that depends on the application.

To access the list inside your class, you first need to create an instance of that class like this:

final Products instanceOfProductsClass = Products(name: 'name', discription: 'discription', image: 'image');
//now using this inscance, access the list. 
final list = instanceOfProductsClass.products;

String image = list[0].image;
String name = list[0].name;
String desc = list[0].discription;

This will solve your null error but will lead to another error. The way you have structured your class is wrong. Here's why. In your class, you are creating a list of type 'Products' which has 5 instances of the same class. Now, each instance of this class in the list will also try to create that same list, and those instances will also try to do the same and this will keep happening until eventually you will get a stack overflow error.

To avoid this, you should not create your list of products in the class itself but rather in your widget where you plan on using it or in a separate file where you manage the data in your app like so:

class Product {


final String name, discription;
final String image;

//List has been removed from the class itself

Product({
    required this.name,
    required this.discription,
    required this.image,
  });
}

And now create your list of products in your widget, like this:

class BodyPage extends StatelessWidget {
final List<Product> products = [
Product(
    name: 'Gaine Plastic',
    discription:
        'Les gaines ou fourreaux de protection utilisables dans l\'habitat 
dépendent de la norme NF C 15-100 relative aux installations électriques à 
basse tension ',
    image: 'assets/images/gainePlastic.png'),
Product(
    name: 'Gaine Plastic',
    discription:
        'Les gaines ou fourreaux de protection utilisables dans l\'habitat 
dépendent de la norme NF C 15-100 relative aux installations électriques à 
basse tension ',
    image: 'assets/images/port.png'),
Product(
    name: 'Gaine Plastic',
    discription:
        'Les gaines ou fourreaux de protection utilisables dans l\'habitat 
dépendent de la norme NF C 15-100 relative aux installations électriques à 
basse tension ',
    image: 'assets/images/Sheet.png'),
Product(
    name: 'Gaine Plastic',
    discription:
        'Les gaines ou fourreaux de protection utilisables dans l\'habitat 
dépendent de la norme NF C 15-100 relative aux installations électriques à 
basse tension ',
    image: 'assets/images/gainePlastic.png'),
Product(
    name: 'Gaine Plastic',
    discription:
        'Les gaines ou fourreaux de protection utilisables dans l\'habitat 
dépendent de la norme NF C 15-100 relative aux installations électriques à 
basse tension ',
    image: 'assets/images/gainePlastic.png'),
];

@override
Widget build(BuildContext context) {
String image = products[0].image;
String name = products[0].name;
String desc = products[0].discription;

return Container(....
AbdulAziz Umar
  • 393
  • 2
  • 9
0

There is something quite weird here. If you pay close attention you can see that the products list is inside the product class. It doesn't make sense to store all the products in the single product class. That causes the problem because in the BodyPage your referencing a null Products object in the build function. You can fix it by extracting the Products list out of the products class and then import it in the products body like that:

product.dart

class Products {
  final String name, discription;
  final String image;
  
  Products({ 
    required this.name, 
    required this.discription, 
    required this.image,
  });
}

List<Products> products = [
    Products(
        name: 'Gaine Plastic',
        discription:
            'Les gaines ou fourreaux de protection utilisables dans l\'habitat dépendent de la norme NF C 15-100 relative aux installations électriques à basse tension ',
        image: 'assets/images/gainePlastic.png'),
    Products(
        name: 'Gaine Plastic',
        discription:
            'Les gaines ou fourreaux de protection utilisables dans l\'habitat dépendent de la norme NF C 15-100 relative aux installations électriques à basse tension ',
        image: 'assets/images/port.png'),
    Products(
        name: 'Gaine Plastic',
        discription:
            'Les gaines ou fourreaux de protection utilisables dans l\'habitat dépendent de la norme NF C 15-100 relative aux installations électriques à basse tension ',
        image: 'assets/images/Sheet.png'),
    Products(
        name: 'Gaine Plastic',
        discription:
            'Les gaines ou fourreaux de protection utilisables dans l\'habitat dépendent de la norme NF C 15-100 relative aux installations électriques à basse tension ',
        image: 'assets/images/gainePlastic.png'),
    Products(
        name: 'Gaine Plastic',
        discription:
            'Les gaines ou fourreaux de protection utilisables dans l\'habitat dépendent de la norme NF C 15-100 relative aux installations électriques à basse tension ',
        image: 'assets/images/gainePlastic.png'),
  ];
  

BodyPage (In the build method - dont forget to import products):

class BodyPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
     String image = products[0].image;
     String name = products[0].name;
     String desc = products[0].discription;
     ...
  }
  ...
}

Yair Chen
  • 917
  • 6
  • 10