как сделать выпадение во флаттере значений через запятую из колонки sqflite - PullRequest
0 голосов
/ 19 сентября 2019

Я хочу выпадающий список, значение которого поступает из базы данных sqflite.примерное значение:

    {
            "id": 5,
            "name": "New",
            "stages": "{\"Lead in\":false,\"Contacted\":false,\"Demo Presented\":false,\"Proposal Sent\":false,\"t4eg4ehhhe4h\":false,\"Extra Features Discussed\":false,\"Negotiation\":false,\"Closure\":false}",
            "created_at": "2019-05-03 17:49:05",
            "updated_at": "2019-06-06 16:16:04",
            "deleted_at": null
        },

мне нужно раскрытие стадий, таких как ввод, контакт, демонстрация, предложение и ниже мой код

                              FutureBuilder(
                              future: pipelineHelper.getPipeStage(pipelineId),
                              builder: (BuildContext context,
                                  AsyncSnapshot<List<Pipeline>>
                                  snapshot) {
                                if (!snapshot.hasData)
                                  return CircularProgressIndicator();
                                return DropdownButton(
                                  items: snapshot.data
                                      .map((stageList) => DropdownMenuItem<Pipeline>(
                                    value: stageList, child: Text(stageList.stages),))
                                      .toList(),
                                  onChanged: (actList) {
                                    setState(() {
                                      stageName = actList.title;
                                      debugPrint('stage selected');
                                    });
                                  },
                                  isExpanded: true,
                                );
                              })

я не знаю, как разделить динамическое будущеесписок, и я получил {\ "Lead in \": false, \ "Contacted \": false, \ "Demo Presented \": false, \ "Предложение отправлено \": false, \ "t4eg4ehhhe4h \": false, \ "Обсуждаются дополнительные функции \ ": false, \" Переговоры \ ": false, \" Закрытие \ ": false} при раскрытии.Ниже приведен мой вспомогательный код

Future<List<Pipeline>> getPipeStage(int number) async {
Database db = await this.database;
var orgMapList = await db.rawQuery('SELECT $colStages from $pipeTable WHERE $colId = $number'); // Get 'Map List' from database
int count = orgMapList.length;
 List<Pipeline> pipeList = List<Pipeline>();
// For loop to create a 'Pipeline List' from a 'Map List'
for (int i = 0; i < count; i++) {
  pipeList.add(Pipeline.fromMapObject(orgMapList[i]));
}
return pipeList;

}

, если я это сделаю, то этапы getter не определены для класса «List». Ошибка была видна

            items: snapshot.data.stages.split(',')

1 Ответ

0 голосов
/ 19 сентября 2019

Если я вас понимаю, ясно
В вашем коде pipeHelper.getPipeStage (pipelineId) возвращает только одну запись PipeLine
Так что конвейер списка AsyncSnapshot должен измениться на конвейер AsyncSnapshot
, и в элементах можно использовать расщепление для разделения запятойи вернуть DropdownMenuItem

items: snapshot.data.stage
                    .split(', ')

полный код

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

void main() => runApp(MyApp());

// To parse this JSON data, do
//
//     final stages = stagesFromJson(jsonString);

List<Pipeline> stagesFromJson(String str) =>
    List<Pipeline>.from(json.decode(str).map((x) => Pipeline.fromJson(x)));

String stagesToJson(List<Pipeline> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Pipeline {
  String pipelineId;
  String stage;

  Pipeline({
    this.pipelineId,
    this.stage,
  });

  factory Pipeline.fromJson(Map<String, dynamic> json) => Pipeline(
        pipelineId: json["pipelineId"],
        stage: json["stage"],
      );

  Map<String, dynamic> toJson() => {
        "pipelineId": pipelineId,
        "stage": stage,
      };
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: JsonApiDropdown(),
    );
  }
}

class JsonApiDropdown extends StatefulWidget {
  @override
  JsonApiDropdownState createState() {
    return new JsonApiDropdownState();
  }
}

class JsonApiDropdownState extends State<JsonApiDropdown> {
  String _currentSelection;

  final String uri = 'https://jsonplaceholder.typicode.com/users';

  Future<Pipeline> _fetchstage() async {
    String jsonString =
        '[ { "pipelineId": "CDG0008", "stage": "stage1, stage2, stage3" }, { "pipelineId": "CDG0004", "stage": "Ceo - Chief Executive Officer" } ]';
    final stages = stagesFromJson(jsonString);
    return stages[0];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Fetching data from JSON - DropdownButton'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            FutureBuilder<Pipeline>(
                future: _fetchstage(),
                builder:
                    (BuildContext context, AsyncSnapshot<Pipeline> snapshot) {
                  if (!snapshot.hasData) return CircularProgressIndicator();
                  return DropdownButton<String>(
                    items: snapshot.data.stage
                        .split(', ')
                        .map((data) => DropdownMenuItem<String>(
                              child: Text(data),
                              value: data,
                            ))
                        .toList(),
                    onChanged: (String value) {
                      setState(() {
                        _currentSelection = value;
                      });
                    },
                    isExpanded: false,
                    //value: _currentUser,
                    hint: Text('Select User'),
                  );
                }),
            SizedBox(height: 20.0),
            _currentSelection != null
                ? Text("selection : " + _currentSelection)
                : Text("No selected"),
          ],
        ),
      ),
    );
  }
}

enter image description here

...