Я новичок во флаттере, и я пытаюсь получить значения из API после выбора пользователя в DropdownButton (с учетом также значения (ов) запроса API в DropdownButton). Моя цель - сделать еще один выпадающий список с этими значениями, но у меня возникает ошибка, когда я пытаюсь принять значение (я).
Это все ошибка в консоли отладки:
Restarted application in 2 436ms.
flutter: test
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: [](0)
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1 _MyListScreenState.onChange
package:chat/main.dart:121
#2 _DropdownButtonState._handleTap.<anonymous closure> (package:flutter/src/material/dropdown.dart)
#3 _rootRunUnary (dart:async/zone.dart:1134:38)
#4 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
#5 _FutureListener.handleValue (dart:async/future_impl.dart:140:1
#6 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:682:45)
#7 Future._propagateToListeners (dart:async/future_impl.dart:711:32)
#8 Future._completeWithValue (dart:async/future_impl.dart:526:5)
#9 Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:556:7)
#10 _rootRun (dart:async/zone.dart:1126:13)
#11 _CustomZone.run (dart:async/zone.dart:1023:19)
#12 _Custo<…>
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method '[]=' was called on null.
Tried calling: []=(0, "RandomValue_Bool")
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1 _MyListScreenState.onChange.<anonymous closure>.<anonymous closure>
package:chat/main.dart:112
#2 _rootRunUnary (dart:async/zone.dart:1134:38)
#3 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
#4 _FutureListener.handleValue (dart:async/future_impl.dart:140:18)
#5 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:682:45)
6 Future._propagateToListeners (dart:async/future_impl.dart:711:32)
#7 Future._completeWithValue (dart:async/future_impl.dart:526:5)
#8 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:34:15)
#9 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:293:13)
#10 _MyListScreenState.wait (package:chat/main.dart)
<asynchronous suspension>
#11 _<…>
То, что я хочу взять и поместить в список (commandsDevice), будет deviceGet[indexDevice].commands[i].name;
таким, как после того, как я могу поместить его в DropdownButton.
Ошибка исходит от этого кода
commandsDevice[i] = deviceGet[indexDevice].commands[i].name;
Так что я думаю, что это асинхронная проблема, поэтому я попытался сделать ее асинхронной с помощью некоторых методов, но мне это не удалось.
Это мой основной код:
import 'dart:convert';
import 'dart:ffi';
import 'package:flutter/material.dart';
import 'Get.dart';
import 'Device.dart';
import 'deviceData.dart';
//Changement
var url1 = "http://localhost:48082/api/v1/device";
// Test
//var url2 = "http://localhost:48082/api/v1/device/name/"+valeurDevice;
// end test
// end changed
// Test
var indexDevice;
// Test end
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
build(context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'My App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyListScreen(),
);
}
}
class MyListScreen extends StatefulWidget {
@override
createState() => _MyListScreenState();
}
class _MyListScreenState extends State {
List<deviceData> dataDevice = deviceData.getDevicesData();
// Test list commamnds
List<String> commandsDevice;
// Test end of list commands
List<DropdownMenuItem<deviceData>> listDropDevice;
deviceData deviceSelection;
// Creation of deviceGet object with device data
var deviceGet = new List<Device>();
Future<void> GetDevice() async {
// changed
await GET.getDevice(url1).then((response) {
//end changed
setState(() {
Iterable list = json.decode(response.body);
deviceGet = list.map((model) => Device.fromJson(model)).toList();
});
});
}
Future<void> wait() async {
await GetDevice();
}
initState() {
super.initState();
wait().then((result) {
//print(deviceGet[1].commands.length);
var nbrDevice = deviceGet.length;
for (int i = 0; i < nbrDevice;) {
//changed
dataDevice.add(deviceData(deviceGet[i].name, i));
//changed
i = i + 1;
}
listDropDevice = buildDropdownMenuItems(dataDevice);
});
}
List<DropdownMenuItem<deviceData>> buildDropdownMenuItems(List devices) {
List<DropdownMenuItem<deviceData>> items = List();
for (deviceData device1 in devices) {
items.add(
DropdownMenuItem(
value: device1,
child: Text(device1.name),
),
);
}
return items;
}
onChange(deviceData selectionUtilisateur) {
setState(() {
deviceSelection = selectionUtilisateur;
// Here it doesn't work well
wait().then((result) {
// test command
indexDevice = selectionUtilisateur.getIndex();
var taille = deviceGet[indexDevice].commands.length;
for (int i = 0; i < taille;) {
//print(deviceGet[indexDevice].commands[i].name);
commandsDevice[i] = deviceGet[indexDevice].commands[i].name;
i = i + 1;
}
//end here it doesn't work well
});
});
// Test commandsDevice list value
print("test");
print( commandsDevice[0]);
//end of the test
}
@override
build(context) {
return Scaffold(
appBar: AppBar(
title: Text("Device List"),
),
body: Column(children: <Widget>[
Center(child: Text("")),
DropdownButton(
value: deviceSelection,
items: listDropDevice,
onChanged: onChange,
hint: Text("Selectionner le device")),
Text(indexDevice.toString()),
]));
}
}
И я уже проверил ( чтобы распечатать его), поэтому я знаю, какие значения я хочу получить.
Спасибо за помощь.