私はいくつかのjsonデータを読み込もうとしていますがfuturebuilder
、最初にデータが利用可能になるのを待ってから表示するために使用しました。にデータを読み込もうとするとDetailsView
、2 つのログ メッセージが表示されます。データがなく、null であるというメッセージが表示され、画面がエラーになり、その後通常に戻り、json がコンソールに記録されます。
スローされる例外はThe following NoSuchMethodError was thrown building FutureBuilder<String>(dirty, state: _FutureBuilderState<String>#cc31b): The method '[]' was called on null. Receiver: null
.
サンプルコード:
body: Container(
margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 15.0),
child: FutureBuilder(
future: DefaultAssetBundle.of(context).loadString("assets/my_data.json"), // validly referenced in pubspec and in right folder
builder: (context, snapshot){
if(!snapshot.hasData){
print('no data'); // I understand it will be empty for now
} else {
print('hd');
}
var data = snapshot.data.toString();
print(data); // null logged to console, is the future still empty at this point?
final parsedData = json.decode(data);
print('pd ${parsedData[1]}'); // this line is where it shows the method [] was called on null
return data == null || data.isEmpty
? LoadingStrengths()
: MyDataText();
// : DailyStrengthText(day: widget.day, data: parsedData);
},
),
),
問題は次のようです。
- 未来をまともに扱っていない
- json を適切に解析していません。そのコピーを以下に添付しました。
サンプルデータ:
[{
"1": "Each day is an opportunity to start over again"
},
{
"2": "Every man must at one point be tempted to hoist the black"
},
{
"3": "Be kind to everyone you meet"
}]
値にアクセスするために、文字列化された数値をキーとして使用して解析しようとしています。これのモデルクラスを作成するか、またはこのjsonをfuturebuilderで解析するにはどうすればよいですか? ありがとう。
- - - - - - - - - - - - - - - - 編集 - - - - - - - - - ---------------------- データを解析して出力することができた、編集されたビルダー メソッドを次に示します。
if(!snapshot.hasData){
print('no data yet');
return LoadingStrengths();
} else {
print('hd');
var data = snapshot.data.toString();
parsedData = json.decode(data);
print('pd ${parsedData[widget.day - 1]}');
}
return Text('${data[widget.day - 1]}'); // it errors out here
Text ウィジェットに値を割り当てると、次のエラー メッセージが表示されます。
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder<String>(dirty, state: _FutureBuilderState<String>#cc19b):
The method '[]' was called on null.
Receiver: null
Tried calling: [](4)
The relevant error-causing widget was:
FutureBuilder<String> file:///E:/FlutterProjects/daily_strength/lib/screens/DetailsView.dart:30:18
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _DetailsViewState.build.<anonymous closure>
(package:daily_strength/screens/DetailsView.dart:47:34)
#2 _FutureBuilderState.build
(package:flutter/src/widgets/async.dart:751:55)
#3 StatefulElement.build
(package:flutter/src/widgets/framework.dart:4744:28)
#4 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:4627:15)
これはどういう意味ですか?データを取得していますが、テキスト ウィジェットに設定しても何らかの理由で機能しませんか? ありがとう。