在Flutter中创建可重用的功能组件

时间:2019-02-13 05:37:13

标签: api dart flutter flutter-dependencies flutter-sliver

我想在扑朔迷离中创建一个可重用的服务组件。在react-native中,我们可以通过belove代码来实现。

export async function Service({
  api,
  third_party,
  method,
  params
}) {
  const headers = {};

  set(headers, 'Cache-Control', 'no-cache');
  set(headers, 'Content-Type', 'application/json');

  const reqBody = {
    method,
    headers,
    timeout: 30 * 1000
  };

  if (!isEmpty(params)) {
    reqBody.body = JSON.stringify(params);
  }

  return fetch(path, reqBody)
    .then(response => response.json())
    .then((data) => {
      console.log('response json data = ', data);
      if (data.errors) {
          if (data.code === 403 && data.number === 1006) {
            emitter.emit('AppRoot:VERSION_UPDATED', data.links);
          }
          return {
            result: 'error',
            ...data
          };
      }
      return {
        result: 'ok',
        ...data
      };
    })
    .catch(() => {
      return {
        result: 'error',
        message: 'Please check your internet connection!'
      };
    });
}

服务组件的使用。

OpenMed_Service,
{
    api: 'patients/add-to-account',
    method: 'POST',
    params: payload
}

Service.dart

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

class Service extends StatelessWidget {
  final String api;
  final String method;
  var params;

  Service({
    this.api,
    this.method,
    this.params
  });

  var headers = {};
  final String url = "http://www.adminapi/somee.com/";
  var reqBody = {
    'header': ('Content-Type', 'application/json'),
    timeout: 30 * 1000
  };

  if (!isEmpty(params)) {
    reqBody.body = json.decode(params);
  }


  @override
  Widget build(BuildContext context) {
    if(method == 'post') {
      Future<http.Response> createPost(Post post) async{
        final response = await http.post('$url',
        headers: reqBody.headers,
        body: json.encode(post));
        return json.decode(response.body);
      }
    } else if(method == 'get') {
      Future<http.Response> getPost() async{
        final response = await http.get('$url/$api');
        return postFromJson(response.body);
      }
    }
  }
}

我尝试创建statlessWidgets,但出现很多错误。我已经创建了服务类,它需要返回小部件,但我想返回JSON数据。

任何人都知道如何在颤动中归档相同的内容。

0 个答案:

没有答案