如何在Flutter中的小部件中创建内部循环?

时间:2019-02-19 06:39:25

标签: dart flutter

我有一个json文件:

[
    {  "1": [
      {"week": "Saturday"},

      { 
        "name": "A",
        "time": "15:30"
      },
      {
        "name": "B", 
        "time": "18:45"
      },
      {
        "name": "C",
        "time": "21:00"
      }
    ]
   },

    {  "2": [
      {"week": "Sunday"},

        {
          "name": "D",
          "time": "14:30"     
        },
        {
          "name": "E",
          "time": "15:00"
        }

      ]
    }

]

这是我的代码。假设counter列表是根据json文件生成的。

import 'dart:convert';

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => new MyAppState();
}

class MyAppState extends State<MyApp> {
  List data;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text("Load local JSON file"),
        ),
        body: new Container(
          child: new Center(
            // Use future builder and DefaultAssetBundle to load the local JSON file
            child: new FutureBuilder(
                future: DefaultAssetBundle
                    .of(context)
                    .loadString('data_repo/data.json'),
                builder: (context, snapshot) {
                  // Decode the JSON
                  var new_data = json.decode(snapshot.data.toString());
                  List counter = [3, 2];


                  return new ListView.builder(

                    // Build the ListView
                    itemBuilder: (BuildContext context, int index) {

                      return new Card(
                        child: new Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: <Widget>[
                            ListTile(
                       title: Text(
                         new_data[index]["${index+1}"][0]["week"],
                         style: Theme.of(context).textTheme.headline,
                       ),
                      ),

                            new Text(new_data[index]["${index+1}"][1]["name"]),
                            new Text(new_data[index]["${index+1}"][1]['time']),

                          ],
                        ),
                      );
                    },
                    itemCount: new_data == null ? 0 : new_data.length,
                  );
                }),
          ),
        ));
  }
}

我的输出: enter image description here

我想以相同的顺序显示json文件的所有对象,即在“星期六”之后,A表示时间,B表示时间,等等。我尝试了两个文本的循环,但无法实现我的目标。如何在小部件中创建一个内部循环以显示所需的内容,或执行此操作的任何其他方式?

1 个答案:

答案 0 :(得分:1)

您需要将-f2套在另一个input_file['days.to.play']中。

ListView.builder

输出:

enter image description here