首页 > 解决方案 > 如何根据json文件中的项目数生成卡片列表

问题描述

我使用以下代码在颤动屏幕上生成 10 张预定义卡片,这些卡片不会改变:

    List cards = new List.generate(10, (i)=>new QuestionCard()).toList();
      @override
      Widget build(BuildContext context) {
          return new Scaffold(
                appBar: new AppBar(
                  title: new Text('My First App'),
                  backgroundColor:new Color(0xFF673AB7),
                ),
                body: new Container(
                  child: new ListView(
                    children: cards,
                  )

                )

            );

        }
    }

class QuestionCard extends StatefulWidget {
  @override
  _QuestionCardState createState() => _QuestionCardState();
}

class _QuestionCardState extends State<QuestionCard> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Card(
        borderOnForeground: true,
        color: Colors.green,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            const ListTile(
              trailing: Icon(Icons.album),
              title: Text('Q1'),
              subtitle: Text('What is the name of this location?'),
            ),
            new TextFormField(
                      decoration: new InputDecoration(
                        labelText: "Answer Question",
                        fillColor: Colors.white,
                        border: new OutlineInputBorder(
                          borderRadius: new BorderRadius.circular(25.0),
                          borderSide: new BorderSide(
                          ),
                        ),
                        //fillColor: Colors.green
                      ),
                      validator: (val) {
                        if(val.length==0) {
                          return "Type your answer here";
                        }else{
                          return null;
                        }
                      },
                      keyboardType: TextInputType.text,
                      style: new TextStyle(
                        fontFamily: "Poppins",
                      ),
                    ),
            ButtonBar(
              children: <Widget>[
                FlatButton(
                  child: const Text('Save'),
                  onPressed: () {/* ... */},
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

我的 json 很简单(questions.json):

{
    "Questions":
    [
        {
            "id" : 1,
            "quest" : ["question one"]
        },
        {
            "id" : 2,
            "quest" : ["question two", "question three"]
        },
        {
            "id" : 3,
            "quest" : ["question four"]
        },
        {
            "id" : 4,
            "quest" : ["question five", "question six", "question seven"]
        }
    ]
}

所以我有 2 个问题需要解决: 1. 如果我有超过 1 个问题,我需要为回复添加一个额外的文本框,我将使用不同的卡片类型,最多 2、3、4 个,我需要定义一次。

  1. 但我真正的问题是:如何根据 json 响应生成列表:

    未来 _loadQuestionAssets() async { return await rootBundle.loadString('assets/questions.json'); }

      Future loadQuestion() async{
        String jsonString = await _loadQuestionAssets();
        final jsonResponse = json.decode(jsonString);
        Questions question = new Questions.fromJson(jsonResponse);
        //List cards = new List.generate(length, generator)
      }
    

标签: jsonflutterflutter-layout

解决方案


尝试这个:

class MyFirstApp extends StatefulWidget{
  @override
  createState()=> new _appState();
}
class _appState extends State<MyFirstApp>{
    List _displayData;
    //assuming that you saved your json file in your assets folder
    loadJson() async {
      String data = await rootBundle.loadString('assets/json/questions.json');
      jsonResult = json.decode(data);
      print(jsonResult);
      setState((){
        _displayData = jsonResult["Questions"];
      });
  }
  @override
  void initState(){
    super.initState();
    loadJson();
  }

  @override
  Widget build(BuildContext context){
    return Scaffold(
      appbar: Appbar(
        title: Text("My APP")
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child: _displayData == null ? Center(child: CircularProgressIndicator()) : 
        ListView.builder(
          itemcount: _displayData.length,
          itembuilder: (context, index){
            return Container(
               width: MediaQuery.of(context).size.width,
               height: 80,
               margin: EdgeInsets.only(bottom: 5),
               child: Text(_displayData[index]["id"])
            );
          }
        )
      )
    );
  }
}

推荐阅读