тип ‘Список’ не является подтипом типа ‘Список’

#json #api #flutter #dart #flutter-dependencies

#json #API #флаттер #dart #флаттер-зависимости

Вопрос:

 import 'package:flutter/material.dart';
import 'package:dropdownfield/dropdownfield.dart';
import 'package:http/http.dart' as http;

class Formwidget extends StatefulWidget {

  @override
  _FormwidgetState createState() => _FormwidgetState();
}

class _FormwidgetState extends State<Formwidget> {


  Map locationDataBangalore;
  fetchlocationData()async{
    http.Response locationData = await http.get("http://192.168.0.102:5000/get_location_names");
    setState(() {
      locationDataBangalore = jsonDecode(locationData.body);
    });
    print(locationDataBangalore['locations']);
  }
  @override
  void initState() {
    fetchlocationData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return locationDataBangalore == null ? Center(child: CircularProgressIndicator(),) :Container(
      child: Column(
        children: <Widget>[
          DropDownField(
            controller: locationController,
            hintText: "Select Location",
            enabled: true,
            items: locationDataBangalore["locations"],
          ),
        ],
      ),
    );
  }
}

final locationController = TextEditingController();
  

Данные Json, поступающие из API «http://192.168.0.102:5000/get_location_names «

 {
"locations": [
"1st block jayanagar",
"1st phase jp nagar",
"2nd phase judicial layout",
"2nd stage nagarbhavi",
"5th block hbr layout",
"5th phase jp nagar",
"6th phase jp nagar",
"7th phase jp nagar",
"8th phase jp nagar",
"9th phase jp nagar",
"aecs layout",
 ]
}
  

Я хочу передать эти данные json в раскрывающемся поле.Выпадающий файл является сторонним виджетом и принимает данные в виде списка строк в своем свойстве, называемом «элементы», но я сталкиваюсь с этой ошибкой. Пожалуйста, помогите мне и дайте мне понять, где я ошибаюсь.

 ════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following _TypeError was thrown building DropDownField(dirty, dependencies: [MediaQuery], state: DropDownFieldState#b3785):
type 'List<dynamic>' is not a subtype of type 'List<String>'

The relevant error-causing widget was: 
  DropDownField file:///home/sidd/AndroidStudioProjects/home_price_predictor/lib/widgets/formWidget.dart:38:11
When the exception was thrown, this was the stack: 
#0      DropDownFieldState._items (package:dropdownfield/dropdownfield.dart:200:30)
#1      new DropDownField.<anonymous closure> (package:dropdownfield/dropdownfield.dart:175:71)
#2      FormFieldState.build (package:flutter/src/widgets/form.dart:526:26)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4792:27)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:15)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
I/SurfaceView(18574): updateWindow -- setFrame, this = io.flutter.embedding.android.FlutterSurfaceView{343db9e V.E...... ......I. 0,0-720,1280}
I/SurfaceView(18574): updateWindow -- OnPreDrawListener, mHaveFrame = true, this = io.flutter.embedding.android.FlutterSurfaceView{343db9e V.E...... ......I. 0,0-720,1280}

════════ Exception caught by rendering library ═════════════════════════════════════════════════════
A RenderFlex overflowed by 99551 pixels on the bottom.
The relevant error-causing widget was: 
  Column file:///home/sidd/AndroidStudioProjects/home_price_predictor/lib/pages/formpage.dart:32:16
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
type 'List<dynamic>' is not a subtype of type 'List<String>'
The relevant error-causing widget was: 
  DropDownField file:///home/sidd/AndroidStudioProjects/home_price_predictor/lib/widgets/formWidget.dart:38:11
════════════════════════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
type 'List<dynamic>' is not a subtype of type 'List<String>'
The relevant error-causing widget was: 
  DropDownField file:///home/sidd/AndroidStudioProjects/home_price_predictor/lib/widgets/formWidget.dart:38:11
════════════════════════════════════════════════════════════════════════════════════════════════════
V/InputMethodManager(18574): START INPUT: io.flutter.embedding.android.FlutterView{b02d67f VFE...... .F....I. 0,0-720,1280} ic=null tba=android.view.inputmethod.EditorInfo@d855bb2 controlFlags=#100
D/ActivityThread(18574): ACT-AM_ON_PAUSE_CALLED ActivityRecord{c04ff16 token=android.os.BinderProxy@4dd8097 {com.example.homepricepredictor/com.example.homepricepredictor.MainActivity}}
D/ActivityThread(18574): ACT-PAUSE_ACTIVITY handled : 0 / android.os.BinderProxy@4dd8097
V/ActivityThread(18574): Finishing stop of ActivityRecord{c04ff16 token=android.os.BinderProxy@4dd8097 {com.example.homepricepredictor/com.example.homepricepredictor.MainActivity}}: show=true win=com.android.internal.policy.PhoneWindow@1647703
D/ActivityThread(18574): ACT-STOP_ACTIVITY_SHOW handled : 0 / android.os.BinderProxy@4dd8097
  

Ответ №1:

Я полагаю, что следующее исправление поможет:

 ...
DropDownField(
            controller: locationController,
            hintText: "Select Location",
            enabled: true,
            items: locationDataBangalore["locations"].cast<String>(),
          ),
...
  

Это происходит потому, что dart обрабатывает значение locationDataBangalore[«locations»] как список динамических значений, поэтому вы должны привести их к String .

Комментарии:

1. Спасибо @Alex Radzishevsky, это сработало. Я также понял концепцию, спасибо!

2. .cast() больше не существует…

3. @Raptor, что вы имеете в виду, говоря, что он больше не существует?