Flutter:使用由swaggerHub

时间:2019-03-11 13:44:52

标签: dart flutter swagger

我正在尝试使用IDE android studio使用Flutter开发移动应用程序,我使用swagger生成包含所有Web服务的Dart文件代码生成,如下所示:我转到“ swagger.io”,然后我用我的帐户登录以摇晃集线器,然后选择“导入Api”,然后将Web服务的网址放入“网址或路径”字段中。之后,我将此文件导出为名为“ dart-client-generation-dart”的飞镖文件。最后,我在flutter项目中导入了此文件,并在pubspec.yaml中添加了缺少的依赖项。我想使用获取所有类别的Web服务之一,并将其​​显示在屏幕上的ListView中。我已经在main.dart中准备了如下的UI:

     import 'package:flutter/material.dart';

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

        class ListUserApp extends StatelessWidget {
          @override
          Widget build(BuildContext context) {
            return MaterialApp(
              title: 'User List 4Motors',
              home: ListUserScreen(),
            );
          }
        }

        class ListUserScreen extends StatefulWidget {
          @override
          State<StatefulWidget> createState() {
            return ListUserScreenState();
          }
        }

        class ListUserScreenState extends State<ListUserScreen> {
          @override
          Widget build(BuildContext context) {
            return MaterialApp(
              theme: ThemeData(
                primarySwatch: Colors.indigo,
              ),
              home: Scaffold(
                appBar: AppBar(
                  title: Text('User List 4Motors'),
                ),
                body: _buildListUser(),
              ),
            );
          }

            @override
      void initState() {
        super.initState();
        _getAllCategories();
      }

      void _getAllCategories() {
        print('Begin');
        try {
           new FrontEndServicesApi()
              .apiFrontEndServicesGetAllCategoriesProductGet()
              .then((categories) {
            print('Category: ');
            print(categories);
          });
        } catch (e) {
          print(e.toString());
        }
      }
            Widget _buildListUser() {
    return ListView.builder(itemBuilder: (context, position) {
      return Card(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Container(
            margin: const EdgeInsets.all(10.0),
            child: Row(
              children: <Widget>[
                Text(
                  'catagory',
                  //categories[position].toString(), // Category name
                  style: TextStyle(
                    fontSize: 22,
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    });
  }
        }

以下是由摇摇欲坠生成的类别模型:

part of swagger.api;

class CustomCategoryData {

  String id = null;


  Map<String, String> name = {};


  Map<String, String> description = {};


  String icon = null;


  String image = null;


  int order = null;


  String color = null;


  List<CustomSubCategory> subCategories = [];

  CustomCategoryData();

  @override
  String toString() {
    return 'CustomCategoryData[id=$id, name=$name, description=$description, icon=$icon, image=$image, order=$order, color=$color, subCategories=$subCategories, ]';
  }

  CustomCategoryData.fromJson(Map<String, dynamic> json) {
    if (json == null) return;
    id =
        json['id']
    ;
    name =
        json['name']
    ;
    description =
        json['description']
    ;
    icon =
        json['icon']
    ;
    image =
        json['image']
    ;
    order =
        json['order']
    ;
    color =
        json['color']
    ;
    subCategories =
      CustomSubCategory.listFromJson(json['subCategories'])
;
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'description': description,
      'icon': icon,
      'image': image,
      'order': order,
      'color': color,
      'subCategories': subCategories
     };
  }

  static List<CustomCategoryData> listFromJson(List<dynamic> json) {
    return json == null ? new List<CustomCategoryData>() : json.map((value) => new CustomCategoryData.fromJson(value)).toList();
  }

  static Map<String, CustomCategoryData> mapFromJson(Map<String, Map<String, dynamic>> json) {
    var map = new Map<String, CustomCategoryData>();
    if (json != null && json.length > 0) {
      json.forEach((String key, Map<String, dynamic> value) => map[key] = new CustomCategoryData.fromJson(value));
    }
    return map;
  }
}

下面的代码是swagger生成的FrontEndServicesApi类:

part of swagger.api;

class FrontEndServicesApi {
  final ApiClient apiClient;

  FrontEndServicesApi([ApiClient apiClient]) : apiClient = apiClient ?? defaultApiClient;

Future<List<CustomCategoryData>> apiFrontEndServicesGetAllCategoriesProductGet() async {
    Object postBody = null;

    // verify required params are set

    // create path and map variables
    String path = "/api/FrontEndServices/GetAllCategoriesProduct".replaceAll("{format}","json");

    // query params
    List<QueryParam> queryParams = [];
    Map<String, String> headerParams = {};
    Map<String, String> formParams = {};

    List<String> contentTypes = [];

    String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";
    List<String> authNames = ["Bearer"];

    if(contentType.startsWith("multipart/form-data")) {
      bool hasFields = false;
      MultipartRequest mp = new MultipartRequest(null, null);

      if(hasFields)
        postBody = mp;
    }
    else {
          }

    var response = await apiClient.invokeAPI(path,
                                             'GET',
                                             queryParams,
                                             postBody,
                                             headerParams,
                                             formParams,
                                             contentType,
                                             authNames);

    if(response.statusCode >= 400) {
      throw new ApiException(response.statusCode, response.body);
    } else if(response.body != null) {
      return 
        (apiClient.deserialize(response.body, 'List<CustomCategoryData>') as List).map((item) => item as CustomCategoryData).toList();
    } else {
      return null;
    }
  }

因此,当我运行Flutter应用程序时,出现了许多错误,如下所示:

  

执行热重启...正在将文件同步到内置的设备Android SDK   对于x86 ...

     

编译器消息:   文件:///home/innovi/.pub-cache/hosted/pub.dartlang.org/http-0.12.0+1/lib/src/browser_client.dart:6:8:   错误:找不到:'dart:html'导入'dart:html';          ^ file:///home/innovi/.pub-cache/hosted/pub.dartlang.org/http-0.12.0+1/lib/src/browser_client.dart:95:25:   错误:找不到类型“ HttpRequest”。虚空   _openHttpRequest(HttpRequest请求,String方法,String url,                           ^^^^^^^^^^^^ file:///home/innovi/.pub-cache/hosted/pub.dartlang.org/http-0.12.0+1/lib/src/browser_client.dart:30 25:   错误:“ HttpRequest”不是类型。最终_xhrs =新   组();                           ^^^^^^^^^^^^^ file:///home/innovi/.pub-cache/hosted/pub.dartlang.org/http-0.12.0+1/lib/src/browser_client.dart:44 :19:   错误:找不到方法:“ HttpRequest”。       var xhr = new HttpRequest();                     ^^^^^^^^^^^^ file:///home/innovi/.pub-cache/hosted/pub.dartlang.org/http-0.12.0+1/lib/src/browser_client.dart:55 :45:   错误:找不到方法:“斑点”。         var blob = xhr.response == null? new Blob([]):xhr.response;                                               ^^^^ file:///home/innovi/.pub-cache/hosted/pub.dartlang.org/http-0.12.0+1/lib/src/browser_client.dart:56:24:   错误:找不到方法:“ FileReader”。         var reader = new FileReader();                          ^^^^^^^^^^^ file:///home/innovi/.pub-cache/hosted/pub.dartlang.org/http-0.12.0+1/lib/src/browser_client.dart:55: 49:   错误:位置参数过多:允许0,但找到1。尝试   删除多余的位置参数。         var blob = xhr.response == null? new Blob([]):xhr.response;                                                   ^ file:///home/innovi/.pub-cache/hosted/pub.dartlang.org/http-0.12.0+1/lib/src/browser_client.dart:95:25:   错误:“ HttpRequest”不是类型。无效_openHttpRequest(HttpRequest   请求,字符串方法,字符串网址,                           ^^^^^^^^^^^^ file:///home/innovi/.pub-cache/hosted/pub.dartlang.org/http-0.12.0+1/lib/src/browser_client.dart:97 :13:   错误:未为类“无效类型”定义方法“打开”。   尝试将名称更正为现有方法的名称,或定义   一种名为“ open”的方法。       request.open(方法,URL,异步:异步,用户:用户,密码:密码);               ^^^^ file:///home/innovi/.pub-cache/hosted/pub.dartlang.org/http-0.12.0+1/lib/src/browser_client.dart:105:11:   错误:未为类“无效类型”定义方法“中止”。   尝试将名称更正为现有方法的名称,或定义   一种名为“中止”的方法。         xhr.abort();             ^^^^^在1331毫秒内重新启动了应用程序。 I / flutter(10372):开始E / flutter(10372):[错误:flutter / lib / ui / ui_dart_state.cc(148)]   未处理的异常:'package:http / src / browser_client.dart':错误:   文件:///home/innovi/.pub-cache/hosted/pub.dartlang.org/http-0.12.0+1/lib/src/browser_client.dart:44:19:   错误:找不到方法:“ HttpRequest”。 E /颤振(10372):var xhr   =新的HttpRequest(); E / flutter(10372):^^^^^^^^^^^^ E / flutter(10372):#0 _AsyncAwaitCompleter.start   (dart:async / runtime / libasync_patch.dart:49:6)E / flutter(10372):#1
  BrowserClient.send(软件包:http / src / browser_client.dart:42:32)   E / flutter(10372):#2 BaseClient._sendUnstreamed   (软件包:http / src / base_client.dart:169:38)E / flutter(10372):    E / flutter(10372):#3 BaseClient.get   (软件包:http / src / base_client.dart:32:7)E / flutter(10372):#4
  ApiClient.invokeAPI   (文件:///home/innovi/development/FlutterProject/flutter_app_ws/lib/dart-client-generated/lib/api_client.dart:193:25)   E /颤振(10372):E /颤振(10372):#5
  FrontEndServicesApi.apiFrontEndServicesGetAllCategoriesProductGet   (文件:///home/innovi/development/FlutterProject/flutter_app_ws/lib/dart-client-generated/lib/api/front_end_services_api.dart:886:36)   E /颤振(10372):E /颤振(10372):#6
  ListUserScreenState._getAllCategories   (package:flutter_app_ws / main.dart:51:12)E / flutter(10372):#7
  ListUserScreenState.initState(包:flutter_app_ws / main.dart:44:5)   E / flutter(10372):#8 StatefulElement._firstBuild   (包:flutter / src / widgets / framework.dart:3846:58)E / flutter   (10372):#9 ComponentElement.mount   (package:flutter / src / widgets / framework.dart:3711:5)E / flutter(10372):

     

10 Element.inflateWidget(package:flutter / src / widgets / framework.dart:2956:14)E / flutter

     

(10372):#11 Element.updateChild   (包:flutter / src / widgets / framework.dart:2759:12)E / flutter   (10372):#12 SingleChildRenderObjectElement.mount   (包:flutter / src / widgets / framework.dart:4876:14)E / flutter   (10372):#13 Element.inflateWidget   (包:flutter / src / widgets / framework.dart:2956:14)E / flutter   (10372):#14 Element.updateChild   (包:flutter / src / widgets / framework.dart:2759:12)E / flutter   (10372):#15 ComponentElement.performRebuild   (包:flutter / src / widgets / framework.dart:3747:16)E / flutter   (10372):#16 Element.rebuild   (package:flutter / src / widgets / framework.dart:3559:5)E / flutter(10372):

     

17 ComponentElement._firstBuild(package:flutter / src / widgets / framework.dart:3716:5)E / flutter(10372):

     

18 ComponentElement.mount(package:flutter / src / widgets / framework.dart:3711:5)E / flutter(10372):

     

19 Element.inflateWidget(package:flutter / src / widgets / framework.dart:2956:14)E / flutter

     

(10372):#20 Element.updateChild   (包:flutter / src / widgets / framework.dart:2759:12)E / flutter   (10372):#21 SingleChildRenderObjectElement.mount   (包:flutter / src / widgets / framework.dart:4876:14)E / flutter   (10372):#22 Element.inflateWidget   (包:flutter / src / widgets / framework.dart:2956:14)E / flutter   (10372):#23 Element.updateChild   (包:flutter / src / widgets / framework.dart:2759:12)E / flutter   (10372):#24 SingleChildRenderObjectElement.mount   (包:flutter / src / widgets / framework.dart:4876:14)E / flutter   (10372):#25 Element.inflateWidget   (包:flutter / src / widgets / framework.dart:2956:14)E / flutter   (10372):#26 Element.updateChild   (包:flutter / src / widgets / framework.dart:2759:12)E / flutter   (10372):#27 SingleChildRenderObjectElement.mount   (包:flutter / src / widgets / framework.dart:4876:14)E / flutter   (10372):#28 Element.inflateWidget   (包:flutter / src / widgets / framework.dart:2956:14)E / flutter   (10372):#29 Element.updateChild   (包:flutter / src / widgets / framework.dart:2759:12)E / flutter   (10372):#30 SingleChildRenderObjectElement.mount   (包:flutter / src / widgets / framework.dart:4876:14)E / flutter   (10372):#31 Element.inflateWidget   (包:flutter / src / widgets / framework.dart:2956:14)E / flutter   (10372):#32 Element.updateChild   (包:flutter / src / widgets / framework.dart:2759:12)E / flutter   (10372):#33 ComponentElement.performRebuild   (包:flutter / src / widgets / framework.dart:3747:16)E / flutter   (10372):#34 Element.rebuild   (package:flutter / src / widgets / framework.dart:3559:5)E / flutter(10372):

     

35 ComponentElement._firstBuild(package:flutter / src / widgets / framework.dart:3716:5)E / flutter(10372):

     

36 StatefulElement._firstBuild(package:flutter / src / widgets / framework.dart:3864:11)E / flutter

     

(10372):#37 ComponentElement.mount   (package:flutter / src / widgets / framework.dart:3711:5)E / flutter(10372):

     

38 Element.inflateWidget(package:flutter / src / widgets / framework.dart:2956:14)E / flutter

     

(10372):#39 Element.updateChild   (包:flutter / src / widgets / framework.dart:2759:12)E / flutter   (10372):#40 ComponentElement.performRebuild   (包:flutter / src / widgets / framework.dart:3747:16)E / flutter   (10372):#41 El

所以,我该如何纠正这些错误,我被困在一个可以帮助我的地方。

0 个答案:

没有答案