Home > Enterprise >  A value of 'List<Homes>?' can't be assigned to a variable of type'List<
A value of 'List<Homes>?' can't be assigned to a variable of type'List<

Time:02-18

why it doesn't work,it worked fine in without null safety something might be missed. but i dont understand what's wrong It would be greate help if you give some time to this

// ignore_for_file: prefer_const_constructors, sized_box_for_whitespace, use_key_in_widget_constructors,prefer_const_literals_to_create_immutables

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:http/http.dart' show get;

import 'dart:convert';


class Homes {
  final String id;
  final String name, addr, image_url, desciption;
  final String price;

  Homes({
    this.id='',
    this.name='',
    this.addr='',
    this.image_url='',
    this.desciption='',
    this.price='',
  });

  factory Homes.fromJson(Map<String, dynamic> jsonData) {
    return Homes( 
      id: jsonData['id'],
      name: jsonData['name'],
      addr: jsonData['addr'],
      desciption: jsonData['desciption'],
      // http://192.168.0.106/flutter/
      image_url: "https://homeshouse.000webhostapp.com/images/"   jsonData['image_url'],
      price: jsonData['price'],
    );
  }
}

class CustomListView extends StatelessWidget {
  final List<Homes> homelist;

  CustomListView(this.homelist);

  Widget build(context) {
    return ListView.builder(
      itemCount: homelist.length,
      itemBuilder: (context, int currentIndex) {
        return createViewItem(homelist[currentIndex], context);
      },
    );
  }

  Widget createViewItem(Homes homelist, BuildContext context) {
    // ignore: unnecessary_new
    return new Padding(
    padding: const EdgeInsets.symmetric(horizontal: 20.0),
    child: Container(
      margin: EdgeInsets.only(top: 10),  //hotel container 
      height: 165,
      width: double.infinity,
      // width: 10,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.0),
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black12,
            offset: Offset(0.0, 4.0),
            blurRadius: 10.0,
          )
        ],
      ),
      child: Stack(
        children: <Widget>[
          Positioned(
            child: Container(
              height: 140,
              width: 135,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10.0),
                  bottomLeft: Radius.circular(10.0),
                ),
                image: DecorationImage(
                  image: NetworkImage(homelist.image_url),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
          Positioned(
            top: 5,
            left: 150, //EDTIED
            right: 20,

            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  '${homelist.name}',
                  style: TextStyle(
                    fontSize: 18.0,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(
                  height: 5,
                ),
                Text(
                  '${homelist.desciption}',
                  style: TextStyle(
                    fontSize: 14.0,
                    color: Colors.grey,
                  ),
                ),
                SizedBox(height: 5),
                Text(
                  '${homelist.addr}',
                  style: TextStyle(
                    fontSize: 14.0,
                    color: Colors.grey,
                  ),
                ),
                SizedBox(height: 5),
                Text(
                  // '\$${hotels[index].price} / night',
                  '${homelist.price} / nigth',
                  style: TextStyle(fontSize: 16, color: Colors.teal),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 2, top: 10),
                  child: Row(
                    children: <Widget>[
                      Icon(
                        Icons.directions_car,
                        color: Colors.orange.shade300,
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      // Icon(
                      //   Icons.hot_tub,
                      //   color: Colors.blue,
                      // ),
                      // SizedBox(
                      //   width: 10,
                      // ),

                      Icon(
                        Icons.fastfood_rounded,
                        color: Colors.orange.shade300,
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Icon(
                        Icons.wifi,
                        color: Colors.orange.shade300,
                      ),
                      SizedBox(
                        width: 15.0,
                      ),
                      ElevatedButton(onPressed: () {
                    //We start by creating a Page Route.
                    //A MaterialPageRoute is a modal route that replaces the entire
                    //screen with a platform-adaptive transition.
                    var route = new MaterialPageRoute(
                      builder: (BuildContext context) =>
                          new SecondScreen(value: homelist),
                    );
                    //A Navigator is a widget that manages a set of child widgets with
                    //stack discipline.It allows us navigate pages.
                    Navigator.of(context).push(route);
                    // }
                      }, child: Text('Book'),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
          
        ],
      ),
    ),
  );
  }
}

//Future is n object representing a delayed computation.
Future<List<Homes>> downloadJSON() async {
  final jsonEndpoint = "https://homeshouse.000webhostapp.com/get.php";
  // " 192.168.0.106/";

  // final Uri url = Uri.parse(jsonEndpoint);
  final response = await get(Uri.parse(jsonEndpoint));

  if (response.statusCode == 200) {
    // final json = "["   response.body   "]";
    // List homelist = (jsonDecode(json) as List<dynamic>) ;
    List homelist = json.decode(response.body);
    return homelist.map((home) => new Homes.fromJson(home)).toList();
  } else
    throw Exception('We were not able to successfully download the json data.');
}

class SecondScreen extends StatefulWidget {
  final Homes value;

  SecondScreen({Key? key, required this.value}) : super(key: key);

  @override
  _SecondScreenState createState() => _SecondScreenState();
}

class _SecondScreenState extends State<SecondScreen> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: new AppBar(title: new Text('Detail Page')),
      body: new Container(
        child: new Center(
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                Padding(
                  child: new Text(
                    'House DETAILS',
                    style: new TextStyle(
                        fontWeight: FontWeight.bold, fontSize: 20.0),
                    textAlign: TextAlign.center,
                  ),
                  padding: EdgeInsets.only(bottom: 20.0),
                ),
                Padding(
                  //`widget` is the current configuration. A State object's configuration
                  //is the corresponding StatefulWidget instance.
                  child: Image.network('${widget.value.image_url}'),
                  padding: EdgeInsets.all(12.0),
                ),
                Padding(
                  child: new Text(
                    'NAME : ${widget.value.name}',
                    style: new TextStyle(fontWeight: FontWeight.bold),
                    textAlign: TextAlign.left,
                  ),
                  padding: EdgeInsets.all(20.0),
                ),
                Padding(
                  child: new Text(
                    'desciption : ${widget.value.desciption}',
                    style: new TextStyle(fontWeight: FontWeight.bold),
                    textAlign: TextAlign.left,
                  ),
                  padding: EdgeInsets.all(20.0),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class Housedetails extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // ignore: unnecessary_new
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: new ThemeData(
        primarySwatch: Colors.deepOrange,
      ),
      // ignore: unnecessary_new
      home: new Scaffold(
      // drawer: Drawer(child: MainDrawer()),

        resizeToAvoidBottomInset: false,
        appBar: new AppBar(title: const Text('Popluar Homes')),
        // ignore: unnecessary_new
        body: new Center(
          //FutureBuilder is a widget that builds itself based on the latest snapshot
          // of interaction with a Future.
          // ignore: unnecessary_new
          child: new FutureBuilder<List<Homes>>(
            future: downloadJSON(),
            //we pass a BuildContext and an AsyncSnapshot object which is an
            //Immutable representation of the most recent interaction with
            //an asynchronous computation.
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                List<Homes> homelist = snapshot.data;
                return new CustomListView(homelist);
              } else if (snapshot.hasError) {
                return Text('${snapshot.error}');
              }
              //return  a circular progress indicator.
              return new CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

void main() {
  runApp(Housedetails());
}
//end

CodePudding user response:

It's not working anymore because now you have null safety on.

With it, variables cannot be null if they haven't got a ? at the end. For example:

String myString = "Hello World"; //This CANNOT be null
String? myString = null; //This CAN be null

In your code, you will need to check if your List<Homes>? is null before using it. You can use a null check ! as:

List<Homes>? myOldList = null;
List<Homes> myNewList = myOldList!; //If myOldList is null, an Exception will be thrown.
List<Homes> myNewList = myOldList ?? []; //If myOldList is null, assign an empty list.

Or, in your FutureBuilder you should check if is not null.

if (snapshot.hasData) {
    if(snapshot.data != null){
        List<Homes> homelist = snapshot.data;
           return new CustomListView(homelist);
           //.......

CodePudding user response:

The reason for the error you're getting is that you're trying to assign a nullable value to a non-nullable. What you can do here is add null check or utilize the bang (!) operator when assigning the value to determine that the object is indeed non-null.

  • Related