Home > Blockchain >  Flutter display server data / response from json
Flutter display server data / response from json

Time:03-15

I have built a page which reads the json from recipeURL and I wish for it to display the product_name value in the json file. However for some reason my future fetchData () class isn't being read as none of the text in my if else statement is being displayed. Am I missing a simple oversight here?

My dart file:

String barcodeResult;
  _testPageState(this.barcodeResult);
String baseURL= "https://world.openfoodfacts.org/api/v0/product/";
String jsonend = ".json";
String recipeURL= "";

List? listResponse;
Map? mapResponse;
Map? listOfResults;
String? itemResult;

@override
Widget build(BuildContext context) {
  recipeURL = baseURL   barcodeResult   jsonend;
  Uri URL = Uri.parse(recipeURL);

  return Scaffold(
    appBar: AppBar(
        backgroundColor: Colors.teal,
        title:Text('Found Your Item',
        style: TextStyle(
        fontFamily: 'Fredoka',
        fontSize: 25,
        ),
        ),
      ),
        //body: fetchData(),
    );
}

Future fetchData() async {
  http.Response response;
  response = await http 
  .get(Uri.parse(recipeURL));

  if (response.statusCode == 200) {
  Text('Page loaded');
    String data = response.body;
    var productName = convert.jsonDecode(data)['product']['product_name'];
    Text(productName);
    
    setState(() {
      mapResponse = json.decode(response.body);
      listOfResults = mapResponse!['product'];
    });
  }
  else {
    Text('error page not loaded');
  }
}

The Json file looks like this:

JSON LINK: enter image description here

CodePudding user response:

try creating a .g.dart file using flutter packages pub run build_runner build. flutter automatically will create your binding class factory. once you have the binding classes created flutter will automatically code your binding class, including nested classes. I personally think automation is the way to handle all interactions with json from the server.

file.dart
factory ProductView.fromJson(Map<String, dynamic> json) =>
      _$ProductFromJson(json);
Map<String, dynamic> toJson() => _$ProductViewToJson(this);

file.g.dart


ProductView _$ProductViewFromJson(Map<String, dynamic> json) {
  return
ProductView(
    json['field1'] as int,
    json['field2'] as String,
    json['field3'] == null
        ? null
        : DateTime.parse(json['field3'] as String),
  );
}

Map<String, dynamic> _$ProjectViewToJson(ProductView instance) =>
    <String, dynamic>{
      'field1': instance.field1,
      'field2': instance.field2,
      'field3': instance.field3?.toIso8601String(),
    };

CodePudding user response:

enter image description here

You can read your json like this

var futuredata = {};
var productname=    futuredata["product"]["product_name"]

Your fetch method like this

 fetchmydata() async {
    var request = p.Request(
        'GET',
        Uri.parse(
            'https://world.openfoodfacts.org/api/v0/product/5060391623139.json'));

    StreamedResponse response = await request.send();

    if (response.statusCode == 200) {
      // print(await response.stream.bytesToString());
      var data = await response.stream.bytesToString();
      futuredata = json.decode(data);
    } else {
      print(response.reasonPhrase);
    }
  }

With model Class SampleModel? Mymodel = null; fetchmydata() async { var request = p.Request( 'GET', Uri.parse( 'https://world.openfoodfacts.org/api/v0/product/5060391623139.json'));

    StreamedResponse response = await request.send();

    if (response.statusCode == 200) {
      // print(await response.stream.bytesToString());
      var data = await response.stream.bytesToString();
      futuredata = json.decode(data);
      Mymodel = SampleModel.fromJson(futuredata);
    } else {
      print(response.reasonPhrase);
    }
  }
  1. in the method we first read data from json as string or text
  2. then we decode the string type or text from server to map type

enter image description here

enter image description here

enter image description here

SampleCode Dartpad live code check

import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:http/http.dart' as p;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

var futuredata = {};

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  @override
  void initState() {}

  fetchmydata() async {
    var request = p.Request(
        'GET',
        Uri.parse(
            'https://world.openfoodfacts.org/api/v0/product/5060391623139.json'));

    StreamedResponse response = await request.send();

    if (response.statusCode == 200) {
      // print(await response.stream.bytesToString());
      var data = await response.stream.bytesToString();
      futuredata = json.decode(data);
    } else {
      print(response.reasonPhrase);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          FutureBuilder(
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting)
                return Center(
                  child: Container(
                    child: CircularProgressIndicator(),
                    height: 50,
                    width: 50,
                  ),
                );
              else if (snapshot.connectionState == ConnectionState.done)
                return ListTile(
                  title: Text(futuredata["product"]["product_name"].toString()),
                  subtitle: Text("France:"  
                      futuredata["product"]["product_name_en"].toString()),
                );
              else {
                return Container(
                  child: CircularProgressIndicator(),
                  height: 50,
                  width: 50,
                );
              }
            },
            future: fetchmydata(),
          )
        ],
      ),
    );
  }
}

Sample ModelClass

///
/// Code generated by jsonToDartModel https://ashamp.github.io/jsonToDartModel/
///
class SampleModelProduct {
/*
{
  "_id": "5060391623139",
  "_keywords": [
    "peanut"
  ],
  "product_name": "Peanut butter",
  "product_name_en": "Peanut butter",
  "product_name_fr": "Peanut butter"
}
*/

  String? Id;
  List<String?>? Keywords;
  String? productName;
  String? productNameEn;
  String? productNameFr;

  SampleModelProduct({
    this.Id,
    this.Keywords,
    this.productName,
    this.productNameEn,
    this.productNameFr,
  });

  SampleModelProduct.fromJson(Map<String, dynamic> json) {
    Id = json['_id']?.toString();
    if (json['_keywords'] != null) {
      final v = json['_keywords'];
      final arr0 = <String>[];
      v.forEach((v) {
        arr0.add(v.toString());
      });
      Keywords = arr0;
    }
    productName = json['product_name']?.toString();
    productNameEn = json['product_name_en']?.toString();
    productNameFr = json['product_name_fr']?.toString();
  }

  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['_id'] = Id;
    if (Keywords != null) {
      final v = Keywords;
      final arr0 = [];
      v!.forEach((v) {
        arr0.add(v);
      });
      data['_keywords'] = arr0;
    }
    data['product_name'] = productName;
    data['product_name_en'] = productNameEn;
    data['product_name_fr'] = productNameFr;
    return data;
  }
}

class SampleModel {
/*
{
  "code": "5060391623139",
  "product": {
    "_id": "5060391623139",
    "_keywords": [
      "peanut"
    ],
    "product_name": "Peanut butter",
    "product_name_en": "Peanut butter",
    "product_name_fr": "Peanut butter"
  },
  "status": 1,
  "status_verbose": "product found"
}
*/

  String? code;
  SampleModelProduct? product;
  int? status;
  String? statusVerbose;

  SampleModel({
    this.code,
    this.product,
    this.status,
    this.statusVerbose,
  });

  SampleModel.fromJson(Map<String, dynamic> json) {
    code = json['code']?.toString();
    product = (json['product'] != null)
        ? SampleModelProduct.fromJson(json['product'])
        : null;
    status = json['status']?.toInt();
    statusVerbose = json['status_verbose']?.toString();
  }

  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['code'] = code;
    if (product != null) {
      data['product'] = product!.toJson();
    }
    data['status'] = status;
    data['status_verbose'] = statusVerbose;
    return data;
  }
}
  • Related