#json #flutter #parsing #flutter-layout
#json #флаттер #разбор #flutter-макет
Вопрос:
Я изучаю, как анализировать файлы JSON в flutter, но когда я получаю данные на экране, они исчезают через секунду. и когда я обновляю экран, он появляется с 4-го или 5-го числа, а затем снова исчезает. Я не знаю причины. пожалуйста, помогите. ниже приведен код.
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
class Loadjsonagain extends StatelessWidget {
List<String> selectedAnsr;
Loadjsonagain({Key key, this.selectedAnsr})
: super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: DefaultAssetBundle.of(context).loadString(
'assets/question_file.json'),
builder: (context, snapshot) {
List mydata = json.decode(snapshot.data.toString());
if (mydata == null) {
return Center(
child: Text('Loading'),
);
}
else {
return AnswersExplanation(mydata: mydata, myanswers: selectedAnsr,);
}
},
),
);
}
}
class AnswersExplanation extends StatefulWidget {
final mydata;
final myanswers;
AnswersExplanation({Key key, @required this.mydata, this.myanswers})
: super(key: key);
@override
_AnswersExplanationState createState() =>
_AnswersExplanationState(mydata: mydata, myanswers: myanswers);
}
class _AnswersExplanationState extends State<AnswersExplanation> {
List mydata;
List myanswers;
_AnswersExplanationState({this.mydata, this.myanswers});
int i = 1;
question with timer
Widget nextquestion(){
if(i <= mydata[0].length){
print(i);
i ;
return buildCard(i);
}
else{
return Container();
}
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body:
ListView.separated(
itemCount: mydata[0].length,
itemBuilder: (context, index) {
return nextquestion();
},
separatorBuilder: (context, index) {
return Divider();
},
),
);
}
Widget buildCard(int k){
return Padding(
padding: EdgeInsets.only(top: 15, right: 15, left: 15),
child: Card(
elevation: 10,
child: Column(
children: [
Text('hello'),
Text(
'Q$k. ${mydata[0][k.toString()]}',
),
Text(
mydata[2][k.toString()],
),
Text(
myanswers[i],
),
Text(
mydata[3][k.toString()],
),
],
),
),
);
}
}
и ниже приведен пример файла JSON, который я использую -:
[
{
"1": "What Will Be The Output Of the Following Code ?na = "p" * 3nprint(a)",
"2": "Which function finds out the Variable type in Python ?",
"3": "Which of the following keyword is used to define a function in Python ?",
"4": "Which of the following is a print Function in Python ?",
"5": "Which function finds out the Variable type in Python ?",
"6": "Which of the following keyword is used to define a function in Python ?",
"7": "Which function finds out the Variable type in Python ?",
"8": "Which of the following keyword is used to define a function in Python ?",
"9": "Which function finds out the Variable type in Python ?",
"10": "Which of the following keyword is used to define a function in Python ?"
},
{
"1": {
"a": "pp",
"b": "ppp",
"c": "3p",
"d": "p3"
},
"2": {
"a": "typedef",
"b": "typeof",
"c": "type",
"d": "find"
},
"3": {
"a": "func",
"b": "def",
"c": "void",
"d": "function"
},
"4": {
"a": "cout",
"b": "print",
"c": "println",
"d": "stderr"
},
"5": {
"a": "typedef",
"b": "typeof",
"c": "type",
"d": "find"
},
"6": {
"a": "func",
"b": "def",
"c": "void",
"d": "function"
},
"7": {
"a": "typedef",
"b": "typeof",
"c": "type",
"d": "find"
},
"8": {
"a": "func",
"b": "def",
"c": "void",
"d": "function"
},
"9": {
"a": "typedef",
"b": "typeof",
"c": "type",
"d": "find"
},
"10": {
"a": "func",
"b": "def",
"c": "void",
"d": "function"
}
},
{
"1": "ppp",
"2": "type",
"3": "def",
"4": "print",
"5": "type",
"6": "def",
"7": "type",
"8": "def",
"9": "type",
"10": "def"
},
{
"1": "Explanation of 1st question",
"2": "Explanation of 2nd question",
"3": "Explanation of 3rd question",
"4": "Explanation of 4th question",
"5": "Explanation of 5st question",
"6": "Explanation of 6st question",
"7": "Explanation of 7st question",
"8": "Explanation of 8st question",
"9": "Explanation of 9st question",
"10": "Explanation of 10st question"
}
]
дайте мне знать, если есть другой способ сделать это…
а ниже приведена ошибка, которую я получаю -:
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown building:
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 379 pos 10: 'data != null'
When the exception was thrown, this was the stack:
#2 new Text (package:flutter/src/widgets/text.dart:379:10)
#3 _AnswersExplanationState.buildCard (package:education/Quiz_Screens/Answers_Explanations_Screen.dart:132:15)
#4 _AnswersExplanationState.nextquestion (package:education/Quiz_Screens/Answers_Explanations_Screen.dart:71:18)
#5 _AnswersExplanationState.build.<anonymous closure> (package:education/Quiz_Screens/Answers_Explanations_Screen.dart:103:20)
#6 new ListView.separated.<anonymous closure> (package:flutter/src/widgets/scroll_view.dart:1261:34)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
Ответ №1:
Сама ошибка является пояснительной. Вы должны проверить наличие TextView, особенно внутри buildCard. Там было много textview, вы должны отлаживать 1 на 1, если mydata содержит какие-либо данные. Также внутри Text() вы можете проверить, как это, чтобы увидеть, является ли оно null или нет, просто чтобы убедиться, что текст пустой или нет.
Text(myanswers[i] != null ? myanswers[i] : ''),
Я полагаю, что во время future builder вы можете это сделать.
if (snapshot.ConnectionState == ConnectionState.waiting) {
return Center(child: CircularLoadingIndicator);
} else {
List mydata = json.decode(snapshot.data.toString());
return AnswersExplanation(mydata: mydata, myanswers: selectedAnsr);
}
Комментарии:
1. здесь я прокомментировал свои ответы, поскольку эти данные поступают с предыдущей страницы, но, тем не менее, они показывают эту ошибку.
Ответ №2:
Я получил это, удалив метод nexquestion() и поместив весь текст в перевернутую запятую, например
Text(
**'Q$i. ${mydata[0][i.toString()]}'**,
),
Text(
**'Correct Answer - ${mydata[2][i.toString()]}'**,
),
теперь данные сохраняются.