如何使用flutter和Dio为POST设置标头

时间:2019-09-13 20:38:28

标签: flutter dart

这是我下面的代码,我被卡住了,请帮忙。

import React from "react";
import ReactExport from "react-export-excel";

const ExcelFile = ReactExport.ExcelFile;
const ExcelSheet = ReactExport.ExcelFile.ExcelSheet;
const ExcelColumn = ReactExport.ExcelFile.ExcelColumn;

const dataSet1 = [
    {
        name: "Johson",
        amount: 30000,
        sex: 'M',
        is_married: true
    },
    {
        name: "Monika",
        amount: 355000,
        sex: 'F',
        is_married: false
    },
    {
        name: "John",
        amount: 250000,
        sex: 'M',
        is_married: false
    },
    {
        name: "Josef",
        amount: 450500,
        sex: 'M',
        is_married: true
    }
];


class Download extends React.Component {
    render() {
        return (
            <ExcelFile element={<button>Download Data</button>}>
                <ExcelSheet data={dataSet1} name="Employees">
                    <ExcelColumn label="Name" value="name"/>
                    <ExcelColumn label="Wallet Money" value="amount"/>
                    <ExcelColumn label="Gender" value="sex"/>
                    <ExcelColumn label="Marital Status"
                                 value={(col) => col.is_married ? "Married" : "Single"}/>
                </ExcelSheet>

            </ExcelFile>
        );
    }
}

它抛出了数据为空的错误。

2 个答案:

答案 0 :(得分:2)

我能够解决问题。

options方法添加可选参数dio.post并使用Options类定义标头:

void getProducts() async {
  String htoken = Utils.prefs.getString("token");
  try {
    Dio dio = Dio();
    Response response = await dio.post("http://URL",
      data: {},
      options: Options(
        headers: {"appusertoken": "$htoken"},
      ));

    print("data coming");
    print(response);
  } on DioError catch (e) {
    print(e.response.data);
    print(e.response.headers);
    print(e.response.request);
  }
}

答案 1 :(得分:-1)

For example :  
   Dio _dio = new Dio();
        _dio.options.contentType = Headers.formUrlEncodedContentType;
        
        _dio.options.headers['Authorization'] = 'bearer $authToken';
    or use :
        final Map<String, dynamic> header = {'Authorization': 'bearer $authToken'};

        enter code here
        final responseData = await _dio.get(
          Apis.account_profit,
          options: RequestOptions(
              method: 'GET', headers: header, baseUrl: Apis.apiBaseUrl),
        );