Как сформировать список карточек на основе количества элементов в файле json - PullRequest
0 голосов
/ 15 апреля 2020

Я использую следующий код для генерации 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 прост (вопросы. 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 макс, которые мне нужно будет определить один раз.

Но мой реальный вопрос здесь: как мне сгенерировать список на основе ответа json:

Future _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)
  }

1 Ответ

1 голос
/ 15 апреля 2020

попробуйте это:

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"])
            );
          }
        )
      )
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...