-1
class Phone{
int? id;
bool? is_new;
String? title;
String? subtitle;
String? picture;
bool? is_buy;
dynamic best_seller;
int? price_without_discount;
int? discount_price;

Phone({
  this.id,
  this.is_new,
  this.title,
  this.subtitle,
  this.picture,
  this.is_buy,
  this.best_seller,
  this.price_without_discount,
  this.discount_price
});
 factory Phone.fromJson(Map <String, dynamic> json) => Phone(
     id: json[MyPhoneKeys.id],
     is_new: json[MyPhoneKeys.is_new],
     title: json[MyPhoneKeys.title],
     subtitle: json[MyPhoneKeys.subtitle],
     picture: json[MyPhoneKeys.picture],
     is_buy: json[MyPhoneKeys.is_buy],
     best_seller: json[MyPhoneKeys.best_seller],
     price_without_discount: json[MyPhoneKeys.price_without_discount],
     discount_price: json[MyPhoneKeys.discount_price]
 );
}

(My screen to display the data)

class CarouselSliderData extends StatefulWidget{
  const CarouselSliderData({super.key});


  @override
  State<CarouselSliderData> createState() => CarouselSliderDataState();
}

class CarouselSliderDataState extends State<CarouselSliderData> {
  int? id;
  bool? is_new;
  String? title;
  String? subtitle;
  dynamic picture;
  bool? is_buy;
  dynamic best_seller;
  int? price_without_discount;
  int? discount_price;

  late Future<dynamic> phoneSpec;

  @override
  void initState() {
    phoneSpec = MyApiService().getDataMocky();
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
     return FutureBuilder<dynamic>(
          future: phoneSpec,
          builder: (context, snapshot) {
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(snapshot.data!.id),
                  Text(snapshot.data!.is_new),
                  Text(snapshot.data!.title),
                  Text(snapshot.data!.subtitle),
                  Text(snapshot.data!.picture),
                  Text(snapshot.data!.is_buy),
                  Text(snapshot.data!.best_seller),
                  Text(snapshot.data!.price_without_discount),
                  Text(snapshot.data!.discount_price),
                ],
              );

          }



          );
  }

  Future<dynamic> getData() async{
    return await MyApiService().getDataMocky().then((value) async{
      if(value != null){
        setState((){
          id = value!.id!;
          is_new = value!.is_new!;
          title = value!.title!;
          subtitle = value!.subtitle!;
          picture = value!.picture!;
         is_buy = value!.is_buy!;
          best_seller = value!.best_seller!;
          price_without_discount = value!.price_without_discount!;
          discount_price = value!.discount_price!;

        });
        return value;
      }
    },
    );/*.catchError((_){
     throw Exception("Exception is caught");
   });*/
  }
}

(my service to get data)

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:my_work/apiService/model.dart';


class MyApiService{

  Future<dynamic> getDataMocky() async {
  final response = await http.get(
    Uri.parse('https://run.mocky.io/v3/654bd15e-b121-49ba-a588-960956b15175')
  );

  if(response.statusCode == 200){
    return Phone.fromJson(json.decode(response.body)[1]);
  }
  return Exception();
  }
}

is my model right for this api json from this api. I want to get data and display them in carousel Slider(i will add it) but get nulls. The Error is saying Null is not subtype of String and nullcheck is used on NULL value and i don't know why and where is my mistake. Thank you very much

Edgar A8
  • 3
  • 3

1 Answers1

2

Text widget doesnt accept nullable string.

Instead of using ! it would be better to check null first, or you can provide default value on null case. Format will be like

if(snapshot.data!=null) Text(snapshot.data.id),

Or

Text(snapshot.data?.id??"got null"),

Or use String format like bellow, it will show null on null case.

Text("${snapshot.data?.id}"),

I will recommend checking understanding-null-safety

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • Thank you, i will try it. But the other parts is ok? I get nulls Why? – Edgar A8 Oct 14 '22 at 20:54
  • Could be issue on response data, some Fields might be empty `price_without_discount` and `discount_price` are empty on response and raise error, .Also change `getData` methods variable same way, those already accept null data, It will be like `id = value?.id;` , didnt test but others might be ok based on error message – Md. Yeasin Sheikh Oct 14 '22 at 20:56
  • 1
    Thanks, i will try to do without errors – Edgar A8 Oct 14 '22 at 21:04
  • can you please explain to me one thing? I dont understand how to get List from api? I need to create model just dynamic or i need to do for all data that contains in the list? – Edgar A8 Oct 14 '22 at 21:09
  • your API returns map, It can be `json.decode(response.body)["home_store"]` for getting `home_store` list, then generate list from this json can be like `final result = json.decode(response.body)["home_store"] as List?; final homeStoreItems = result.map((r)=>Phone.fromJson(r)).toList()`, you can check [my sample note](https://github.com/yeasin50/Flutter-project-Helper/blob/master/jsonFormating/sample1.dart) and [networking/parsing](https://docs.flutter.dev/cookbook/networking/background-parsing) – Md. Yeasin Sheikh Oct 14 '22 at 21:17
  • Thank you very much, I did it works, i got data but only strings. Because of Text Widget? Sorry if i asked a lot of questions. I'm a beginner – Edgar A8 Oct 14 '22 at 21:29
  • Text widget are used to show string on UI, you can explore [/ui/widgets](https://docs.flutter.dev/development/ui/widgets) to explore other widgets – Md. Yeasin Sheikh Oct 14 '22 at 21:36
  • glad to help, you can also check [cookbook](https://docs.flutter.dev/cookbook) – Md. Yeasin Sheikh Oct 14 '22 at 21:41
  • ok i will read what you sent – Edgar A8 Oct 14 '22 at 21:52