Как отобразить сложные данные json в виде списка во флаттере

#json #flutter

Вопрос:

Это сложные данные json

Я пытаюсь закодировать этот сложный json и отобразить список. Я не могу найти правильный ответ на этот вопрос в переполнении стека. Надеюсь, это поможет кому-то, кто является новичком в флаттере.

Ответ Json

 {
    "product": "astro",
    "init": "2021083118",
    "dataseries": [{
        "timepoint": 3,
        "cloudcover": 5,
        "seeing": 7,
        "transparency": 5,
        "lifted_index": -1,
        "rh2m": 12,
        "wind10m": {
            "direction": "NE",
            "speed": 2
        },
        "temp2m": 28,
        "prec_type": "none"
    }, {
        "timepoint": 6,
        "cloudcover": 5,
        "seeing": 6,
        "transparency": 5,
        "lifted_index": -4,
        "rh2m": 10,
        "wind10m": {
            "direction": "NE",
            "speed": 2
        },
        "temp2m": 29,
        "prec_type": "none"
    }, {
        "timepoint": 9,
        "cloudcover": 4,
        "seeing": 6,
        "transparency": 3,
        "lifted_index": -1,
        "rh2m": 6,
        "wind10m": {
            "direction": "E",
            "speed": 2
        },
        "temp2m": 33,
        "prec_type": "rain"
    }, {
        "timepoint": 12,
        "cloudcover": 6,
        "seeing": 6,
        "transparency": 3,
        "lifted_index": -4,
        "rh2m": 6,
        "wind10m": {
            "direction": "E",
            "speed": 3
        },
        "temp2m": 33,
        "prec_type": "rain"
    }, {
        "timepoint": 15,
        "cloudcover": 9,
        "seeing": 7,
        "transparency": 3,
        "lifted_index": -1,
        "rh2m": 6,
        "wind10m": {
            "direction": "E",
            "speed": 3
        },
        "temp2m": 33,
        "prec_type": "rain"
    }, {
        "timepoint": 18,
        "cloudcover": 9,
        "seeing": 7,
        "transparency": 3,
        "lifted_index": -1,
        "rh2m": 7,
        "wind10m": {
            "direction": "SE",
            "speed": 3
        },
        "temp2m": 32,
        "prec_type": "rain"
    }, {
        "timepoint": 21,
        "cloudcover": 2,
        "seeing": 6,
        "transparency": 4,
        "lifted_index": -1,
        "rh2m": 9,
        "wind10m": {
            "direction": "SE",
            "speed": 2
        },
        "temp2m": 30,
        "prec_type": "none"
    }, {
        "timepoint": 24,
        "cloudcover": 3,
        "seeing": 7,
        "transparency": 4,
        "lifted_index": -1,
        "rh2m": 9,
        "wind10m": {
            "direction": "SE",
            "speed": 2
        },
        "temp2m": 29,
        "prec_type": "none"
    }, {
        "timepoint": 27,
        "cloudcover": 1,
        "seeing": 7,
        "transparency": 4,
        "lifted_index": -1,
        "rh2m": 10,
        "wind10m": {
            "direction": "E",
            "speed": 2
        },
        "temp2m": 28,
        "prec_type": "rain"
    }, {
        "timepoint": 30,
        "cloudcover": 2,
        "seeing": 6,
        "transparency": 4,
        "lifted_index": -4,
        "rh2m": 9,
        "wind10m": {
            "direction": "E",
            "speed": 2
        },
        "temp2m": 29,
        "prec_type": "rain"
    }, {
        "timepoint": 33,
        "cloudcover": 4,
        "seeing": 6,
        "transparency": 3,
        "lifted_index": -4,
        "rh2m": 6,
        "wind10m": {
            "direction": "E",
            "speed": 2
        },
        "temp2m": 33,
        "prec_type": "rain"
    }, {
        "timepoint": 36,
        "cloudcover": 6,
        "seeing": 6,
        "transparency": 3,
        "lifted_index": -1,
        "rh2m": 5,
        "wind10m": {
            "direction": "E",
            "speed": 2
        },
        "temp2m": 34,
        "prec_type": "rain"
    }, {
        "timepoint": 39,
        "cloudcover": 9,
        "seeing": 6,
        "transparency": 3,
        "lifted_index": -1,
        "rh2m": 6,
        "wind10m": {
            "direction": "SW",
            "speed": 2
        },
        "temp2m": 32,
        "prec_type": "rain"
    }, {
        "timepoint": 42,
        "cloudcover": 9,
        "seeing": 6,
        "transparency": 3,
        "lifted_index": -1,
        "rh2m": 8,
        "wind10m": {
            "direction": "SE",
            "speed": 2
        },
        "temp2m": 32,
        "prec_type": "rain"
    }, {
        "timepoint": 45,
        "cloudcover": 5,
        "seeing": 6,
        "transparency": 4,
        "lifted_index": -4,
        "rh2m": 10,
        "wind10m": {
            "direction": "S",
            "speed": 2
        },
        "temp2m": 30,
        "prec_type": "none"
    }, {
        "timepoint": 48,
        "cloudcover": 6,
        "seeing": 6,
        "transparency": 5,
        "lifted_index": -1,
        "rh2m": 11,
        "wind10m": {
            "direction": "S",
            "speed": 2
        },
        "temp2m": 29,
        "prec_type": "none"
    }, {
        "timepoint": 51,
        "cloudcover": 9,
        "seeing": 6,
        "transparency": 5,
        "lifted_index": -1,
        "rh2m": 11,
        "wind10m": {
            "direction": "SW",
            "speed": 1
        },
        "temp2m": 28,
        "prec_type": "none"
    }, {
        "timepoint": 54,
        "cloudcover": 7,
        "seeing": 6,
        "transparency": 5,
        "lifted_index": -4,
        "rh2m": 10,
        "wind10m": {
            "direction": "NE",
            "speed": 2
        },
        "temp2m": 29,
        "prec_type": "rain"
    }, {
        "timepoint": 57,
        "cloudcover": 5,
        "seeing": 6,
        "transparency": 3,
        "lifted_index": -4,
        "rh2m": 6,
        "wind10m": {
            "direction": "SE",
            "speed": 2
        },
        "temp2m": 33,
        "prec_type": "rain"
    }, {
        "timepoint": 60,
        "cloudcover": 6,
        "seeing": 6,
        "transparency": 3,
        "lifted_index": -4,
        "rh2m": 6,
        "wind10m": {
            "direction": "S",
            "speed": 2
        },
        "temp2m": 35,
        "prec_type": "rain"
    }, {
        "timepoint": 63,
        "cloudcover": 8,
        "seeing": 6,
        "transparency": 3,
        "lifted_index": -4,
        "rh2m": 6,
        "wind10m": {
            "direction": "SW",
            "speed": 3
        },
        "temp2m": 34,
        "prec_type": "rain"
    }, {
        "timepoint": 66,
        "cloudcover": 8,
        "seeing": 6,
        "transparency": 4,
        "lifted_index": -1,
        "rh2m": 8,
        "wind10m": {
            "direction": "S",
            "speed": 3
        },
        "temp2m": 32,
        "prec_type": "rain"
    }, {
        "timepoint": 69,
        "cloudcover": 3,
        "seeing": 6,
        "transparency": 4,
        "lifted_index": -1,
        "rh2m": 10,
        "wind10m": {
            "direction": "S",
            "speed": 3
        },
        "temp2m": 29,
        "prec_type": "none"
    }, {
        "timepoint": 72,
        "cloudcover": 3,
        "seeing": 6,
        "transparency": 5,
        "lifted_index": -1,
        "rh2m": 11,
        "wind10m": {
            "direction": "S",
            "speed": 2
        },
        "temp2m": 28,
        "prec_type": "none"
    }]
}
 

Это основной класс, в котором я вызываю класс модели и храню данные в

главная.дротик

 import 'dart:async';

import 'dart:convert';

import 'package:flutter/material.dart';

import 'package:http/http.dart' as http;

import '7Timer.dart';

void main() {

  runApp(new MaterialApp(

    home: new HomePage()

  ));

}

class HomePage extends StatefulWidget {   @override   HomePageState createState() => new HomePageState(); }

class HomePageState extends State<HomePage> {

  late String p;

  late String i;

  late List<Dataseries> d;

  Future<String> getData() async {

    var response = await http.get(

      Uri.parse("https://www.7timer.info/bin/astro.php?

lon=113.2amp;lat=23.1amp;ac=0amp;unit=metricamp;output=jsonamp;tzshift=0"),
      
    );


   Map<String,dynamic>  userMap = jsonDecode(response.body);

   var timer = Timer.fromJson(userMap);  

    setState(() {

      p=timer.product;

      i=timer.init;

      d=timer.data;

    });

    return "Success!";   }

  @override

  void initState(){

    this.getData();

  }

  @override

  Widget build(BuildContext context){
    
    return new Scaffold(

      appBar: new AppBar(title: new Text("Listviews"), backgroundColor: Colors.blue),

      body: new ListView.builder(

        itemCount: d == null ? 0 : d.length,

        itemBuilder: (BuildContext context, int index){

          return new Card(

            child: new Text('timepoint=${d[index].timepoint} seeing=${d[index].seeing} cloudcover=${d[index].cloudcover} seeing=${d[index].seeing}'),

          );

        },

      ),

    );

  }

}
 

Это класс модели.

7Тимер.дротик

 class Timer {

  final String product;

  final String init;

  final List<Dataseries> data;

  Timer({required this.product, required this.init, required this.data});

List<Dataseries>.fromJson(json['dataseries'].map((s)=>Dataseries.fromJson(s)));

 factory Timer.fromJson(Map<String, dynamic> json) {

    var list = json['dataseries'] as List;

    print(list.runtimeType);

    List<Dataseries> dataList = list.map((i) => Dataseries.fromJson(i)).toList();

    return Timer(

      product:json['product'],

        init:json['init'],

        data:dataList,
    );

  }

  get length => null;

  Map<String, dynamic> toJson() => {

        'product': product,

        'init': init,

      };

}

class Dataseries {

  int timepoint;

  int cloudcover;

  int seeing;

  int transparency;

  int lifted_index;

  int rh2m;

  Dataseries(this.timepoint, 

this.cloudcover,this.seeing,this.transparency,this.lifted_index,this.rh2m);

  Dataseries.fromJson(Map<String, dynamic> json)
      : timepoint = json['timepoint'],
        cloudcover = json['cloudcover'],
        seeing = json['seeing'],
        transparency = json['transparency'],
        lifted_index = json['lifted_index'],
        rh2m = json['rh2m'];

    Map<String, dynamic> toJson() => {
        'timepoint': timepoint,
        'cloudcover': cloudcover,
        'seeing' : seeing, 
        'transparency' : transparency,
        'lifted_index' : lifted_index,
        'rh2m' : rh2m
      }; }
 

Комментарии:

1. О чем wind10m ? и при извлечении данных, какие ошибки вы извлекаете. И используйте FutureBuilder на корпусе лесов.

Ответ №1:

Этот файл называется main.dart. Я изменил код. Изначально я не могу использовать и найти какой-либо ответ, связанный с использованием списка в будущем построителе, и я не могу его использовать.

Спасибо Равиндре С. Патил за вашу помощь.

 import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '7Timer.dart';

void main() {
  runApp(new MaterialApp(
    home: new HomePage()
  ));
}

class HomePage extends StatefulWidget {
  @override
  HomePageState createState() => new HomePageState();
}

class HomePageState extends State<HomePage> {
  Future<List<Dataseries>> getData() async {
    var response = await http.get(
      Uri.parse("https://www.7timer.info/bin/astro.php?lon=113.2amp;lat=23.1amp;ac=0amp;unit=metricamp;output=jsonamp;tzshift=0"),
      
    );
    

         Map<String,dynamic>  userMap = jsonDecode(response.body);
   var timer = Timer.fromJson(userMap);  
    
    return timer.data;
  }

  @override
  void initState(){
    // this.getData();
  }

  @override
  Widget build(BuildContext context){
    
    return new Scaffold(
      appBar: new AppBar(title: new Text("Listviews"), backgroundColor: Colors.blue),
        body:Center(
    child: FutureBuilder<List<Dataseries>>(
      future: getData(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return Padding(
            padding: const EdgeInsets.all(8.0),
            child: ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) {
                var id = snapshot.data![index].cloudcover;
                var pp = snapshot.data![index].timepoint;
                var st = snapshot.data![index].seeing;
                var na = snapshot.data![index].lifted_index;
              
                return Card(
                  shape: RoundedRectangleBorder(
                    side: BorderSide(
                      color: Colors.green.shade300,
                    ),
                    borderRadius: BorderRadius.circular(15.0),
                  ),
                  child: ListTile(
                    // leading: Text('progress_percentage=${snapshot.data![index].progress_percentage} status=${snapshot.data![index].status}}'),
                    // title: Text(type),
                    leading:Text('${id} ${pp}')
                  ),
                );
              },
            ),
          );
        }
        return CircularProgressIndicator();
      },
    ),
  ),
    );
  }
}