Как заполнить данные из конечной точки REST API Django с помощью всплывающего виджета - PullRequest
0 голосов
/ 16 февраля 2019

У меня есть внутренняя сборка с Django REST, с некоторыми конечными точками.Мне нужно отобразить список состояний стран с помощью выпадающего виджета Flutter.Но мне трудно отобразить список состояний в раскрывающемся списке.Что я делаю не так и как мне заставить это работать.

Я следовал этому руководству на флаттере doc https://flutter.io/docs/cookbook/networking/background-parsing

, но я до сих пор не могу заставить его работать.

Вот ошибка, которую я получаю.


Compiler message:
lib/src/ui/musicrelease/song_upload_page.dart:458:26: Error: The method
'[]' isn't defined for the class '#lib1::States'.
Try correcting the name to the name
of an existing method, or defining a method named '[]'.
            value: states['id'].toString(),
                         ^^
lib/src/ui/musicrelease/song_upload_page.dart:460:21: Error: The method '[]' isn't definedfor the class '#lib1::States'.
Try correcting the name to the name of an existing method, or defining a method named '[]'.
              states['name'],
                    ^^lib/src/ui/musicrelease/song_upload_page.dart:492:16: Error: Getter not found: 'data'.
        items: data.map((dropDownStringItem) {
               ^^^^
lib/src/ui/musicrelease/song_upload_page.dart:492:16: Error: The getter 'data' isn't defined for the class '#lib1::SongUploadPageState'.
Try correcting the name to the name of an existing getter, or defining a getter or field named 'data'.        items: data.map((dropDownStringItem) {
               ^^^^
Compiler failed on C:\Users\AZEEZ\IdeaProjects\vibespotcodebase\vibespot\lib/main.dartGradle task 'assembleDebug'... Done                         60.1s
Gradle task assembleDebug failedwith exit code 1



Ниже приведен пример моего кода:

Конечная точка

http://localhost/api/state/

model.dart

 import 'dart:convert';

List<States> parseStates(String responseBody) {
  final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();

  return parsed.map<States>((json) => States.fromJson(json)).toList();
}

class States {
  String id;
  String name;
  String countryId;

  States({
    this.id,
    this.name,
    this.countryId,
  });

  factory States.fromJson(Map<String, dynamic> json) => new States(
        id: json["id"],
        name: json["name"],
        countryId: json["country_id"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "country_id": countryId,
      };
}

services.dart

import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:vibespot/src/models/dashboard/state_model.dart';


Future<List<States>> fetchStates() async {
  final response = await http.get('http://localhost:8000/api/state/');
final responsebody = parseStates(response.body);
setState(() {
      states = responsebody;

    });
  return parseStates(response.body);
}

ui.dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:vibespot/src/models/dashboard/state_model.dart';
import 'package:vibespot/src/services/dashboard/state_local_services.dart';
import 'dart:io';

class SongUploadPage extends StatefulWidget {
  @override
  SongUploadPageState createState() => SongUploadPageState();
}

class SongUploadPageState extends State<SongUploadPage> {
  var _currentItemSelected ;
  String _mySelection;
  List<States> states = [];

 @override
  void initState() {
    super.initState();
    fetchStates();

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text("Track",
            style: TextStyle(
              fontSize: 25,
              color: Colors.orange.shade700,
            )),
      ),

      body: Center(
        child: ListView(
            shrinkWrap: true,
            padding: EdgeInsets.only(left: 20.0, right: 20.0),
            children: <Widget>[
              stateList(),
              SizedBox(height: 20.0),
              submitReleaseBotton(),
            ]),
      ),
    );
  }

  Widget stateList() {
    return Container(
      // color: Colors.black,
      child: DropdownButtonFormField<String>(
        decoration: InputDecoration(
          hintText: 'Select State',
          filled: true,
          fillColor: Colors.white,
          hintStyle: TextStyle(color: Colors.black),
          contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10.0),
          ),
          // labelText: 'Number of tracks'
        ),
        items: states.map((States map) {
          return DropdownMenuItem<String>(
            value: map.id.toString(),
            child: Text(
              map.name,
              style: TextStyle(
                color: Colors.white,
              ),
            ),
          );
        }).toList(),
        onChanged: (String newValueSelected) {
          setState(() {
            this._currentItemSelected = newValueSelected;
          });
        },
        value: _currentItemSelected,
      ),
    );
  }
}

1 Ответ

0 голосов
/ 16 февраля 2019

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

items: states.map((States states) {
  return DropdownMenuItem<String>(
    value: states.id.toString(),
    child: Text(
      states.name.toString,
      style: TextStyle(
        color: Colors.white,
      ),
    ),
  );
}).toList(),

States - это класс, содержащий атрибуты id и name, и вы пытаетесь получить к ним доступ через states['id'], что для Json.Таким образом, вы должны получить к ним доступ через states.id и states.name соответственно.

...